Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple global interceptors in NestJS

I had already know we could create global interceptors from this code below:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
  ],
})
export class AppModule {}

Source: documentation

However, what if I want to have let say, UserInterceptor.
UserInterceptor will get user from database and transform the request.
UserInterceptor need to inject let say UserService.
And I want to use UserInterceptor globally.

@Injectable()
export class UserInterceptor {
  constructor(private readonly service: UserService) {}
}

From documentation, we can't do app.useGlobalInterceptors(new UserInterceptor()) because UserInterceptor need 1 argument in the constructor (UserService).

And since we had use APP_INTERCEPTOR for LoggingInterceptor, I didn't found another way to assign another value to APP_INTERCEPTOR to use the interceptor globally.
For example I think the problem will solved if we could do:

providers: [
  {
    provide: APP_INTERCEPTOR,
    useClass: [LoggingInterceptor, UserInterceptor]
  }
]
like image 990
Ivan Elianto Avatar asked Mar 01 '23 14:03

Ivan Elianto


1 Answers

providers: [
  {
    provide: APP_INTERCEPTOR,
    useClass: LoggingInterceptor
  },
  {
    provide: APP_INTERCEPTOR,
    useClass: UserInterceptor
  }
]

Just like this

like image 175
cojack Avatar answered Mar 08 '23 14:03

cojack