0
votes

I have an interceptor in my api-gateway, which transforms rpc-exceptions to http-exceptions. The interceptor is placed in a shared directory without any module in it.

In my controllers I use the interceptor like so:

import { GrpcErrorsInterceptor } from 'shared/grpc-errors.interceptor';

@Controller('mycontroller')
@UseInterceptors(new GrpcErrorsInterceptor())
export class MyController { }

On the other side, I've seen approaches where the interceptor is added to the providers array in a module:

import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: MyInterceptor,
    },
  ],
})
export class SharedModule { }    

So what is the better approach in terms of the "nest-way"? And how would I inject the interceptor to my controllers in the second example?

1

1 Answers

2
votes

Both of these approaches are fine. The big thing to think about with binding your interceptors is do you want the interceptor to be bound globally or only to a class or route? By using the APP_INTERCEPTOR custom provider method, you are binding the interceptor globally, so make sure you have all edge cases handled if you do that. Otherwise you can do @UseInterceptors(GrpcErrorsInterceptor) and still get Nest to use DI (if necessary) and bind the interceptor to only a class or a route.