In NestJs can I use an interceptor and the @Response parameter status setter?

663 views Asked by At

I have a NestJs application that uses an interceptor to wrap all http responses much like the example in the docs https://docs.nestjs.com/interceptors ...

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(map(data => ({ data })));
  }
}

For most endpoints this is good enough, but I've found some instances where I want to set the response code based on some logic in the controller, e.g.:

@UseInterceptors(TransformInterceptor)
@Post('some-path')
async someFunction(
  @Response() reply: Fastify.FastifyReply,
) {
  return reply
    .status(isATeapot ? HttpStatus.I_AM_A_TEAPOT : HttpStatus.OK)
    .send(someData);
}

But, in this latter case the interceptor gets called with undefined and the response that hits the wire is just the raw data.

Is there a way to get both the interceptor and the branching in the status code?

1

There are 1 answers

4
Jay McDoniel On BEST ANSWER

Use @Response({ passthrough: true }) and don't .send() the response, to be able to just set the HTTP code and let Nest still handle the response

@UseInterceptors(TransformInterceptor)
@Post('some-path')
async someFunction(
  @Response({ passthrough: true }) reply: Fastify.FastifyReply,
) {
  reply
    .status(isATeapot ? HttpStatus.I_AM_A_TEAPOT : HttpStatus.OK)
  return someData;
}