4

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();
}

1 Answers1

8

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.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • How can I use `createMicroservice` with configService? – huykon225 Oct 14 '21 at 03:07
  • I think the OP has answered his own question correctly for nest js microservices. Thank you OP. The example in this answer is for a regular HTTP service. Which is also useful. – Gavin S Dec 22 '21 at 17:02
  • I think you should expand on this answer to describe the configure() method. It's not clear how to configure an app after it is created. For me, I had to create the configureService before creating the app, otherwise the wrong MQTT options would be used. This answer helped: https://stackoverflow.com/a/70070499/632088 – Rusty Rob Sep 19 '22 at 22:49