Search code examples
nestjsnestjs-jwt

NestJS - Use service inside Interceptor (not global interceptor)


I have a controller that uses custom interceptor:

Controller:

@UseInterceptors(SignInterceptor)
    @Get('users')
    async findOne(@Query() getUserDto: GetUser) {
        return await this.userService.findByUsername(getUserDto.username)
    }

I have also I SignService, which is wrapper around NestJwt:

SignService module:

@Module({
    imports: [
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                privateKey: configService.get('PRIVATE_KEY'),
                publicKey: configService.get('PUBLIC_KEY'),
                signOptions: {
                    expiresIn: configService.get('JWT_EXP_TIME_IN_SECONDS'),
                    algorithm: 'RS256',
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [SignService],
    exports: [SignService],
})
export class SignModule {}

And Finally SignInterceptor:

@Injectable()
export class SignInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        return next.handle().pipe(map(data => this.sign(data)))
    }

    sign(data) {
        const signed = {
            ...data,
            _signed: 'signedContent',
        }

        return signed
    }
}

SignService works properly and I use it. I would like to use this as an interceptor How can I inject SignService in to SignInterceptor, so I can use the functions it provides?


Solution

  • I assume that SignInterceptor is part of the ApiModule:

    @Module({
      imports: [SignModule], // Import the SignModule into the ApiModule.
      controllers: [UsersController],
      providers: [SignInterceptor],
    })
    export class ApiModule {}
    

    Then inject the SignService into the SignInterceptor:

    @Injectable()
    export class SignInterceptor implements NestInterceptor {
      constructor(private signService: SignService) {}
    
      //...
    }
    

    Because you use @UseInterceptors(SignInterceptor) to use the interceptor in your controller Nestjs will instantiate the SignInterceptor for you and handle the injection of dependencies.