Javascript 当承诺在嵌套中解析为未定义时,如何返回404HTTP状态码?

Javascript 当承诺在嵌套中解析为未定义时,如何返回404HTTP状态码?,javascript,node.js,nestjs,typeorm,Javascript,Node.js,Nestjs,Typeorm,为了避免样板代码(一遍又一遍地检查每个控制器中是否存在未定义的代码),当getOne中的承诺返回未定义的代码时,如何自动返回404错误 @Controller('/customers') export class CustomerController { constructor ( @InjectRepository(Customer) private readonly repository: Repository<Customer> ) { } @Get(

为了避免样板代码(一遍又一遍地检查每个控制器中是否存在未定义的代码),当
getOne
中的承诺返回未定义的代码时,如何自动返回404错误

@Controller('/customers')
export class CustomerController {
  constructor (
      @InjectRepository(Customer) private readonly repository: Repository<Customer>
  ) { }

  @Get('/:id')
  async getOne(@Param('id') id): Promise<Customer|undefined> {
      return this.repository.findOne(id)
         .then(result => {
             if (typeof result === 'undefined') {
                 throw new NotFoundException();
             }

             return result;
         });
  }
}
@Controller(“/customers”)
导出类CustomerController{
建造师(
@InjectRepository(客户)专用只读存储库:存储库
) { }
@获取(“/:id”)
异步getOne(@Param('id')id):承诺{
返回此.repository.findOne(id)
。然后(结果=>{
如果(结果类型===‘未定义’){
抛出新的NotFoundException();
}
返回结果;
});
}
}
Nestjs提供了与TypeORM的集成,在示例存储库中是一个TypeORM
存储库
实例。

您可以编写一个在
未定义
上抛出
NotFoundException

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> { {
    // next.handle() is an Observable of the controller's result value
    return next.handle()
      .pipe(tap(data => {
        if (data === undefined) throw new NotFoundException();
      }));
  }
}


谢谢工作得很好!最好将拦截器定义为工厂,这意味着无需调用
newnotfoundinterceptor()
即可传递参数。你知道怎么做吗?太好了!:-)查看中的
useFactory
。您可以将工厂的参数作为提供程序本身注入。根据您的用例,这可能是您所需要的。
// Apply the interceptor to *all* endpoints defined in this controller
@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {
  
// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
  return Promise.resolve(undefined);
}