【问题标题】:How to get Nestjs configService instance in main.ts before instantiating app如何在实例化应用程序之前在 main.ts 中获取 Nestjs configService 实例
【发布时间】:2021-06-10 19:05:07
【问题描述】:

我的应用实例取决于配置:serviceName 在这种情况下

const serviceName = 'authentication-service'
const servicePrefix = `api/${serviceName}`;
const swaggerPrefix = 'swagger';
...
const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      requestIdLogLabel: serviceName,
      logger: true,
      ...
    }),
    {
      // logger: ['log']
      logger: process.env.DEV === '1' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
    });

NestJs documentation 使用应用实例获取configService 单例:

const configService = app.get(ConfigService);
const port = configService.get('PORT');

在实例化我的应用之前有什么方法可以获取configService 实例?

【问题讨论】:

    标签: nestjs nestjs-config


    【解决方案1】:

    不。您可以自己调用dotenvconfig() 方法并填充process.env,如果您真的需要的话,仅此而已。从技术上讲,如果你真的想要,你可以创建一个NestFactory.createApplicationContext() 调用并从那里获取ConfigService,关闭上下文并使用标准NestFactory.create 启动应用程序,但这最终会执行两次DI 解析,这启动速度会很慢

    【讨论】:

    • 感谢您的快速回复! NestJs 似乎在这里失去了一些东西。一个好的框架可以简化事情并尝试涵盖大多数用例。这些标准用例之一是获取配置并使用它来引导应用程序(这就是 Spring 框架所做的)。他们在这里反过来做!
    【解决方案2】:

    我也有类似的需求(对于 Mikro-ORM 配置文件)。我所做的就是创建一个ConfigService的新实例:

    import {ConfigService} from '@nestjs/config'
    const configService = new ConfigService
    

    然后我可以使用configService 来获取端口号:

    configService.get<number>('PSQL_PORT', 5432)
    

    【讨论】:

      【解决方案3】:

      您需要做的是在实际应用之前创建一个虚拟应用实例。

        const configApp = await NestFactory.create(AppModule);
        let configService = configApp.get(ConfigService);
      
        const app = await NestFactory.create<NestFastifyApplication>(
          AppModule,
          new FastifyAdapter({
            requestIdLogLabel: serviceName,
            logger: true,
            ...
          }),
          {
            // logger: ['log']
            logger: process.env.DEV === '1' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
          });
          //...
      

      【讨论】:

        猜你喜欢
        • 2021-01-22
        • 1970-01-01
        • 2015-02-23
        • 1970-01-01
        • 2019-11-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        相关资源
        最近更新 更多