[英]How to get the configurations from within a module import in NestJS?
假设我的模块定义如下:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
// Use ConfigService here
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
PrismaModule,
],
providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}
现在,如何在这里从ConfigService
获取secretKey
?
您必须使用registerAsync
,以便可以注入ConfigService
。 使用它,您可以导入模块,注入提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secretOrPrivateKey: configService.getString('SECRET_KEY'),
signOptions: {
expiresIn: 3600,
},
}),
inject: [ConfigService],
}),
有关更多信息,请参见异步选项docs 。
或者还有另一种解决方案,创建一个JwtStrategy类,如下所示:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.session.secret,
issuer: config.uuid,
audience: config.session.domain
});
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
在那里,您可以将ConfigService
作为参数传递给构造函数,但是我仅从纯文件使用config。
然后,不要忘记将其放在模块的提供者数组中。
问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.