Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
gremo Avatar asked Aug 05 '18 15:08

gremo


1 Answers

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);
}
like image 118
Kim Kern Avatar answered Oct 15 '22 13:10

Kim Kern