是否可以为同一ROUTE指定多个处理程序?
任何对/ test路由的HTTP GET请求都应调用 get 处理程序,除非查询字符串watch ==='1',在这种情况下,应改为调用watch处理程序。
import { Controller, Get } from '@nestjs/common';
@Controller('test')
export class TestController {
@Get()
get(){
return 'get'
}
@Get('?watch=1')
watch(){
return 'get with watch param'
}
}
由于该框架似乎不支持此功能,所以我希望能够编写一个装饰器来抽象该逻辑。
即。
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'
}
}
可以做到吗?谁能指出我正确的方向?
关于, 大卫(Davide)
答案 0 :(得分:1)
我会尽量降低复杂度,并简单地实现两个功能。
@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.'
}
}