Search code examples
javascriptnode.jsnestjstypeorm

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


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.


Solution

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