在 NestJS 模块中使用配置服务的最佳实践

新手上路,请多包涵

我想使用环境变量来配置 HttpModule 每个模块,从 文档 中我可以使用这样的配置:

 @Module({
  imports: [HttpModule.register({
    timeout: 5000,
    maxRedirects: 5,
  })],
})

但是我不知道从环境 vairable(或配置服务)中包含 baseURL 的最佳做法是什么,例如:

 @Module({
imports: [HttpModule.register({
    baseURL:  this.config.get('API_BASE_URL'),
    timeout: 5000,
    maxRedirects: 5,
})],

this.configundefined 这里是因为它不在课堂上。

从环境变量(或配置服务)设置 baseURL 的最佳做法是什么?

原文由 Siavash Ahmadpour 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 679
2 个回答

1 月 19 日更新

HttpModule.registerAsync() 已通过此 拉取请求 添加到版本 5.5.0 中。

 HttpModule.registerAsync({
  imports:[ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    baseURL:  configService.get('API_BASE_URL'),
    timeout: 5000,
    maxRedirects: 5,
  }),
  inject: [ConfigService]
}),


原帖

本期 讨论了这个问题。对于像 TypeOrmModuleMongooseModule 这样的 nestjs 模块,实现了以下模式。

useFactory 方法返回配置对象。

 TypeOrmModule.forRootAsync({
  imports:[ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    type: configService.getDatabase()
  }),
  inject: [ConfigService]
}),

尽管卡米尔 写道

以上约定现在应用于所有嵌套模块,并将被视为最佳实践(+对第 3 方模块的建议)。更多在文档中

它似乎没有为 HttpModule 实现,但也许你可以打开一个关于它的问题。我上面提到的问题还有一些其他的建议。

另请查看官方 文档,了解如何实施 ConfigService 的最佳实践。

原文由 Kim Kern 发布,翻译遵循 CC BY-SA 4.0 许可协议

虽然这个问题的最高评分答案在技术上对大多数实现都是正确的,但 @nestjs/typeorm 包和 TypeOrmModule 的用户应该使用看起来更像下面的实现。

 // NestJS expects database types to match a type listed in TypeOrmModuleOptions
import { TypeOrmModuleOptions } from '@nestjs/typeorm/dist/interfaces/typeorm-options.interface';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [mySettingsFactory],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        type: configService.get<TypeOrmModuleOptions>('database.type', {
          infer: true, // We also need to infer the type of the database.type variable to make userFactory happy
        }),
        database: configService.get<string>('database.host'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true,
        logging: true,
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [],
})
export class AppRoot {
  constructor(private connection: Connection) {}
}

这段代码所做的主要事情是从 TypeORM 中检索正确的类型(参见导入)并使用它们来提示返回值 configService.get() 方法。如果你不使用正确的 TypeORM 类型,Typescript 就会生气。

原文由 Andrew Benbow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题