如何从 NestJS 的模块导入中获取配置? [英] How to get the configurations from within a module import in NestJS?

查看:86
本文介绍了如何从 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 {}

现在如何从这里的 ConfigService 获取 secretKey ?

Now how can I get the secretKey from the ConfigService in here?

推荐答案

你必须使用 registerAsync,这样你才能注入你的 ConfigService.有了它,您可以导入模块、注入提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:

You have to use registerAsync, so you can inject your 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.

这篇关于如何从 NestJS 的模块导入中获取配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆