最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return a 404 HTTP status code when promise resolve to undefined in Nest? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Aug 5, 2018 at 23:36 Kim Kern 60.7k20 gold badges219 silver badges214 bronze badges asked Aug 5, 2018 at 15:52 gremogremo 48.6k80 gold badges272 silver badges447 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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);
}
发布评论

评论列表(0)

  1. 暂无评论