简体   繁体   English

如何从NestJS中导入的模块中获取配置?

[英]How to get the configurations from within a module import in NestJS?

Let's say I have my module defined as below: 假设我的模块定义如下:

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      // Use ConfigService here
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    PrismaModule,
  ],
  providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}

Now how can I get the secretKey from the ConfigService in here? 现在,如何在这里从ConfigService获取secretKey

You have to use registerAsync , so you can inject your ConfigService . 您必须使用registerAsync ,以便可以注入ConfigService With it, you can import modules, inject providers and then use those providers in a factory function that returns the configuration object: 使用它,您可以导入模块,注入提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:

JwtModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    secretOrPrivateKey: configService.getString('SECRET_KEY'),
    signOptions: {
        expiresIn: 3600,
    },
  }),
  inject: [ConfigService],
}),

For more information, see the async options docs . 有关更多信息,请参见异步选项docs

Or there is another solution, create an JwtStrategy class, something like this: 或者还有另一种解决方案,创建一个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;
    }
}

There you are able to pass ConfigService as a parameter to the constructor, but I'm using config just from plain file. 在那里,您可以将ConfigService作为参数传递给构造函数,但是我仅从纯文件使用config。

Then, don't forget to place it in array of providers in module. 然后,不要忘记将其放在模块的提供者数组中。

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM