Search code examples
node.jsmicroservicesnestjs

Right way to get ConfigService when bootstrap microservice


I would like to know if i'm getting ConfigService the right way during bootstrap my microservice.

Is there a way to do it using 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();
}

Solution

  • Yes there is a way to do it in the NestFactory, you're already doing it the right way! If you'd like another example, this is my bootstrap function:

    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')}`
      );
    }
    

    Where MyLogger is a custom implementation of the Nest default logger and configure(app, config) is a lot of application configuration done in a separate file to keep the bootstrap function lean and easy to maintain. Of course, the "listening at ..." also needs to be changed before heading to production, but this app is still in development for me.

    The only thing I would suggest to you is changing

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

    to

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

    using the generics for app.get() to give you the type information.