当承诺在 Nest 中解析为 undefined 时,如何返回 404 HTTP 状态代码?

gre*_*emo 6 javascript node.js typeorm nestjs

为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当承诺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;
         });
  }
}
Run Code Online (Sandbox Code Playgroud)

Nestjs 提供了与 TypeORM 的集成,在示例存储库中是一个 TypeORMRepository实例。

Kim*_*ern 4

您可以编写一个抛出on的拦截器NotFoundExceptionundefined

@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();
      }));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器中使用拦截器。您可以在每个类或方法中使用它:

// Apply the interceptor to *all* endpoints defined in this controller
@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {
  
Run Code Online (Sandbox Code Playgroud)

或者

// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
  return Promise.resolve(undefined);
}
Run Code Online (Sandbox Code Playgroud)