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

2023-12-30

为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当 Promise 时,如何自动返回 404 错误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 的集成,示例存储库中是一个 TypeORMRepository实例。


你可以写一个拦截器 https://docs.nestjs.com/interceptors抛出一个NotFoundException on undefined:

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

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

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

or

// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
  return Promise.resolve(undefined);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 Nest 中的 Promise 解析为 undefined 时,如何返回 404 HTTP 状态代码? 的相关文章