首页 > 解决方案 > 引导微服务时获取 ConfigService 的正确方法

问题描述

我想知道在引导我的微服务期间我是否以正确的方式获得了 ConfigService。

有没有办法使用 NestFactory.createMicroservice() 来做到这一点?

async function bootstrap() {
  const app = await NestFactory.create(CoreModule, {
    logger: new MyLogger(),
  });
  const configService: ConfigService = app.get(ConfigService);
  app.connectMicroservice({
    transport: Transport.TCP,
    options: {
      port: configService.PORT,
    },
  });
  await app.startAllMicroservicesAsync();
}

标签: node.jsmicroservicesnestjs

解决方案


是的,在 NestFactory 中有一种方法可以做到这一点,您已经以正确的方式做到了!如果你想要另一个例子,这是我的引导函数:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: new MyLogger()
  });
  const config = app.get<ConfigService>(ConfigService);
  const port = config.get('PORT');
  configure(app, config);
  await app.listen(port);
  scribe.info(
    `Listening at http://localhost:${port}/${config.get('GLOBAL_PREFIX')}`
  );
}

MyLoggerNest 默认记录器的自定义实现在哪里,并且configure(app, config)大量应用程序配置在单独的文件中完成,以保持bootstrap功能精简和易于维护。当然,“收听...”也需要在投入生产之前进行更改,但这个应用程序对我来说仍在开发中。

我唯一建议你的是改变

const configService: ConfigService = app.get(ConfigService);

const configService = app.get<ConfigService>(ConfigService);

使用泛型为app.get()您提供类型信息。


推荐阅读