【问题标题】:NestJS - Use service inside Interceptor (not global interceptor)NestJS - 在拦截器中使用服务(不是全局拦截器)
【发布时间】:2020-12-16 11:48:49
【问题描述】:

我有一个使用自定义拦截器的控制器:

控制器:

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

我还有我的 SignService,它是 NestJwt 的包装器:

SignService 模块:

@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 {}

最后是 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 工作正常,我使用它。我想用它作为拦截器 如何将 SignService 注入到 SignInterceptor 中,以便使用它提供的功能?

【问题讨论】:

    标签: nestjs nestjs-jwt


    【解决方案1】:

    我假设SignInterceptorApiModule 的一部分:

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

    然后将SignService注入SignInterceptor

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

    因为您使用@UseInterceptors(SignInterceptor) 来使用控制器中的拦截器,Nestjs 将为您实例化SignInterceptor 并处理依赖项的注入。

    【讨论】:

    • 发布问题后不久,我做了同样的事情。无论如何谢谢。答案已接受
    猜你喜欢
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2015-11-22
    • 2020-06-29
    • 1970-01-01
    • 2019-09-07
    • 2013-06-25
    • 2018-08-09
    相关资源
    最近更新 更多