Search code examples
apache-kafkamicroservicesnestjskafkajs

Nest.js Inject kafka client to the service


I have a Nest.js microservice application. For message broker between MS I'm using kafka.

Now I want to inject this same connection inside health service to test it's state. I don't want to create a new client and new connection. I need the one which is created in main.ts.

const microserviceOptions = {
  transport: Transport.KAFKA,
  options: {
    client: {
      clientId: `id`,
      brokers: [brokers],
    },
    consumer: {
      groupId: 'group-id',
    },
  },
};

Ideally I would love to get kafkajs client directly from nestjs, to create producers and consumers.


Solution

  • If anyone is stuck searching for this. I extended existing kafka transprot strategy into a custom transporter and imported that.

    I extended ServerKafka into a new class CustomServerKafka. New class only had getConsumer and getProducer, because consumer and producer were protected in ServerKafka.

    I used singleton class creator to get access to active consumer