我有一个使用自定义拦截器的控制器:
控制器:
@UseInterceptors(SignInterceptor)
@Get('users')
async findOne(@Query() getUserDto: GetUser) {
return await this.userService.findByUsername(getUserDto.username)
}
Run Code Online (Sandbox Code Playgroud)
我还有 SignService,它是 NestJwt 的包装器:
签到服务模块:
@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 {}
Run Code Online (Sandbox Code Playgroud)
最后是 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
}
}
Run Code Online (Sandbox Code Playgroud)
SignService 工作正常并且我使用它。我想用它作为拦截器如何将SignService注入到SignInterceptor中,以便我可以使用它提供的功能?
Bab*_*boo 11
我认为这SignInterceptor
是以下内容的一部分ApiModule
:
@Module({
imports: [SignModule], // Import the SignModule into the ApiModule.
controllers: [UsersController],
providers: [SignInterceptor],
})
export class ApiModule {}
Run Code Online (Sandbox Code Playgroud)
然后将其SignService
注入SignInterceptor
:
@Injectable()
export class SignInterceptor implements NestInterceptor {
constructor(private signService: SignService) {}
//...
}
Run Code Online (Sandbox Code Playgroud)
因为您习惯@UseInterceptors(SignInterceptor)
在控制器中使用拦截器,Nestjs 将为SignInterceptor
您实例化并处理依赖项的注入。
归档时间: |
|
查看次数: |
7869 次 |
最近记录: |