0

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?

okhobb
  • 758
  • 8
  • 22

1 Answers1

1

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;
}
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • That works, thanks! ... it's ok that the `reply.status` call is a dangling promise? – okhobb Nov 05 '22 at 07:34
  • Didn't realize that was a promise. You could `await` it if you need to – Jay McDoniel Nov 05 '22 at 16:36
  • Adding `await` seems to not resolve so that is not viable. But, looking more carefully at https://github.com/fastify/fastify/blob/68914519a3fd65ce65ba8db8962940eecf7f0fc8/types/reply.d.ts I'm not convinced it actually is a promise (I thought it was because eslint was telling me as much, but maybe eslint is just checking for the presence of a `then` function). – okhobb Nov 05 '22 at 21:31
  • Also, "patthrough" should be "passthrough" above in the inline code. Thanks again for the pointer!! – okhobb Nov 07 '22 at 03:48