在NestJS模块中使用配置服务的最佳做法 [英] Best practice to use config service in NestJS Module

查看:618
本文介绍了在NestJS模块中使用配置服务的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用环境变量来配置 docs 中每个模块的HttpModule 我可以使用如下配置:

I want to use environment variables to configure the HttpModule per module, from the docs I can use the configuration like this:

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

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

But I don't know what is the best practice to inclue a baseURL from environment vairable (or a config service), for example like this:

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

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

The this.config is undefined here cause it's out of class.

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

What is the best practice to set baseURL from environment variables (or config service)?

推荐答案

更新1月19日

HttpModule.registerAsync()在5.5.0版中添加了拉取请求.

Update Jan 19

HttpModule.registerAsync() was added in version 5.5.0 with this pull request.

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


原始帖子

此问题在问题中进行了讨论.对于TypeOrmModuleMongooseModule之类的nestjs模块,实现了以下模式.


Original Post

This problem was discussed in this issue. For the nestjs modules like the TypeOrmModule or the MongooseModule the following pattern was implemented.

useFactory方法返回配置对象.

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

尽管Kamil

以上约定现在适用于所有嵌套模块,并且将 被视为最佳做法(针对第三方模块的建议). 文档中的更多内容

Above convention is now applied in all nest modules and will be treated as a best practice (+recommendation for 3rd party modules). More in the docs

它似乎还没有为HttpModule实现,但是也许您可以提出一个问题.我在上面提到的问题中还有其他建议.

it does not seem to be implemented for the HttpModule yet, but maybe you can open an issue about it. There are also some other suggestions in the issue I mentioned above.

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

Also have a look at the official docs with best practices on how to implement a ConfigService.

这篇关于在NestJS模块中使用配置服务的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆