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

Sia*_*our 17 javascript node.js typescript nestjs

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

@Module({
  imports: [HttpModule.register({
    timeout: 5000,
    maxRedirects: 5,
  })],
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Kim*_*ern 27

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]
}),
Run Code Online (Sandbox Code Playgroud)

原帖

这个问题在本期讨论过。对于像TypeOrmModuleMongooseModule以下模式的 Nestjs 模块已实现。

useFactory方法返回配置对象。

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

虽然卡米尔写道

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

它似乎HttpModule尚未实施,但也许您可以提出有关它的问题。我上面提到的问题还有一些其他的建议。

还可以查看官方文档,其中包含有关如何实现ConfigService.


And*_*bow 5

尽管这个问题的最高评价答案对于大多数实现来说在技术上是正确的@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) {}
}

Run Code Online (Sandbox Code Playgroud)

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