代码之家  ›  专栏  ›  技术社区  ›  gremo

当promise解析为undefined in Nest时,如何返回404 HTTP状态码?

  •  3
  • gremo  · 技术社区  · 7 年前

    为了避免样板代码(一次又一次地检查每个控制器中是否有未定义的代码),在 getOne 返回未定义?

    @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;
             });
      }
    }
    

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kim Kern    7 年前

    你可以写一个 interceptor 这会导致 NotFoundException undefined :

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

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

    // 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);
    }