Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In nestjs, is it possible to specify multiple handlers for the same route?

Tags:

nestjs

Is it possible to specify multiple handler for the same route?

Any HTTP GET request to the /test route should call the get handler unless the query string watch === '1', in which case it should call the watch handler instead.

import { Controller, Get } from '@nestjs/common';

@Controller('test')
export class TestController {
  @Get()
  get(){
    return 'get'
  }

  @Get('?watch=1')
  watch(){
    return 'get with watch param'
  }
}

As the framework does not seem to support this, I was hoping to be able to write a decorator to abstract this logic.

ie.

import { Controller, Get } from '@nestjs/common';
import { Watch } from './watch.decorator';

@Controller('test')
export class TestController {
  @Get()
  get(){
    return 'get'
  }

  @Watch()
  watch(){
    return 'get with watch param'
  }
}

Can this be done? Can anyone point me to the right direction?

like image 821
Davide Talesco Avatar asked Oct 28 '25 08:10

Davide Talesco


1 Answers

I would try to keep the complexity low and simply implement two functions.

@Controller('test')
export class TestController {
    myService: MyService = new MyService();

    @Get()
    get(@Query('watch') watch: number) {
        if (watch) {
            return myService.doSomethingB(watch);
        } else {
            return myService.doSomethingA();
        }
    }
}

export class MyService {
    doSomethingA(): string {
        return 'Do not watch me.'
    }

    doSomethingB(watch: number): string {
        return 'Watch me for ' + watch + ' seconds.'
    }
}
like image 102
JWo Avatar answered Oct 30 '25 13:10

JWo