How to return a 404 HTTP status code when promise resolve to undefined in Nest?

纵饮孤独 提交于 2021-02-08 15:12:21

问题


In order to avoid boilerplate code (checking for undefined in every controller, over and over again), how can I automatically return a 404 error when the promise in getOne returns undefined?

@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 provides an integration with TypeORM and in the example repository is a TypeORM Repository instance.


回答1:


You can write an interceptor that throws a 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();
      }));
  }
}

Then use the interceptor in your controller. You can use it per class or method:

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


来源:https://stackoverflow.com/questions/51695868/how-to-return-a-404-http-status-code-when-promise-resolve-to-undefined-in-nest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!