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

标签 javascript node.js typescript 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,这样您就可以注入(inject)您的 ConfigService。使用它,您可以导入模块、注入(inject)提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:

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

有关详细信息,请参阅 async options docs .

关于javascript - 如何从 NestJS 的模块导入中获取配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308318/

相关文章:

javascript - Leaflet - 使用 latLon + 距离(米)+ Angular (度)创建标记

javascript - 是否可以使用NODE.JS(或PYTHON)开发ACM ONLINE JUDGE系统?

node.js - mongoose findById 在我使用字符串文字时有效,但在引用对象的属性时无效

node.js - 使用集群模块运行 Node.js 应用程序在 Heroku 中毫无意义?

java - c :forEach issue when part of javascript function

javascript - onClick 来自数据库的随机播放按钮

node.js - DigitalOcean : Domain works with www. 但不是没有?

angular - 如何在自定义组件宿主元素上使用自定义指令

css - Snackbar 动态颜色变化 Angular 7

typescript - 编译 typescript 时找不到名称 'Symbol'