NestJS - 在拦截器中使用服务(不是全局拦截器)

标签 nestjs nestjs-jwt

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

Controller :

@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 注入(inject)到 SignInterceptor 中,以便使用它提供的功能?

最佳答案

我假设 SignInterceptorApiModule 的一部分:

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

然后将SignService注入(inject)SignInterceptor:

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

  //...
}

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

关于NestJS - 在拦截器中使用服务(不是全局拦截器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63618612/

相关文章:

nestjs - 将一个 Guard 应用于 Nestjs 中的多个路由

javascript - NestJS 如何使用 async/await 配置中间件?

javascript - 如何使用Nest.js在开发中提供MockService?

unit-testing - nestjs 中的单元测试中间件

typescript - NestJs JWT 身份验证返回 401

authentication - NestJS jwt-passport 认证

nestjs - UnauthorizedException 作为内部服务器错误交付

dependency-injection - 如何将反射器传递给 Nest.js 全局守卫?