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

THp*_*ubs 6 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 {}
Run Code Online (Sandbox Code Playgroud)

现在我怎样才能secretKeyConfigService这里得到?

Kim*_*ern 16

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

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

有关更多信息,请参阅异步选项文档

  • 另外,如果您已经在应用程序模块中全局导入了 ConfigModule,则无需导入 ConfigModule。即 ConfigModule.forRoot({ isGlobal: true, ExpandVariables: true, }), (3认同)