我想使用环境变量来配置每个模块的HttpModule,在docs中我可以使用如下配置:
@Module({
imports: [HttpModule.register({
timeout: 5000,
maxRedirects: 5,
})],
})但我不知道从环境变量(或配置服务)中获取baseURL的最佳实践是什么,例如:
@Module({
imports: [HttpModule.register({
baseURL: this.config.get('API_BASE_URL'),
timeout: 5000,
maxRedirects: 5,
})],这里的this.config是undefined,因为它不在类中。
从环境变量(或配置服务)设置baseURL的最佳实践是什么?
发布于 2018-11-22 20:21:31
更新1月19日
在版本5.5.0中使用此pull request添加了HttpModule.registerAsync()。
HttpModule.registerAsync({
imports:[ConfigModule],
useFactory: async (configService: ConfigService) => ({
baseURL: configService.get('API_BASE_URL'),
timeout: 5000,
maxRedirects: 5,
}),
inject: [ConfigService]
}),原创帖子
此issue中讨论了此问题。对于像TypeOrmModule或MongooseModule这样的nestjs模块,实现了以下模式。
useFactory方法返回configuration对象。
TypeOrmModule.forRootAsync({
imports:[ConfigModule],
useFactory: async (configService: ConfigService) => ({
type: configService.getDatabase()
}),
inject: [ConfigService]
}),尽管Kamil wrote
上述
约定现已应用于所有嵌套模块,并将被视为最佳实践(第三方模块的+建议)。文档中有更多信息
它似乎还没有在HttpModule上实现,但也许你可以打开一个关于它的问题。在我上面提到的问题中还有一些其他的建议。
另外,还可以查看官方的docs,其中包含如何实现ConfigService的最佳实践。
发布于 2019-11-12 17:48:52
我在实现ConfigService时也遇到了NestJS文档中描述的几个问题(没有类型安全,没有配置值的模块化,...),我在这里非常详细地写下了我们公司的最终NestJS配置管理策略:NestJS Configuration Management
基本思想是有一个中央配置模块,它从进程的环境中加载所有配置值。但是,每个模块可以注入配置值的专用子集,而不是向所有模块提供单个服务!因此,每个模块都包含一个类,该类指定了该模块需要在运行时提供的所有配置值。这同时为开发人员提供了对配置值的类型安全访问(而不是在整个代码库中使用字符串文字)
希望此模式也适用于您的用例:)
发布于 2022-02-02 21:00:42
尽管这个问题的最高评级答案在技术上对大多数实现都是正确的,但@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) {}
}https://stackoverflow.com/questions/53426486
复制相似问题