NestJs initialize module similar to moduleInit while being Request scoped

Viewed 32

I need to initialise a Kafka consumer at module initialisation. But the service I'm setting this up in has a dependency on a REQUEST scoped service. Because of this, moduleInit inside my kafka consumer service is not being triggered. I'm not sure how I'd settle this.

What alternatives are available to me here?

Eg

requestScoped.service.ts

@Injectable()
export class RequestScopedService {
  constructor(
    @Inject(REQUEST) private request: Request,
  ) {}

kafka.consumer.ts

@Injectable()
export class KafkaConsumer implements OnModuleInit {
  constructor(
    private requestScopedService: RequestScopedService,
  )

  async onModuleInit() {
    console.log ('I need to set up my kafka consumer here');
    const consumer = kafka.consumer({ groupId: 'my-group' })
    await consumer.connect()

    await consumer.subscribe({ topics: ['topic-A'] })
    await consumer.run({
        eachMessage: async ({ topic, partition, message, heartbeat, pause }) => {
            console.log (" I will listen to all incoming messages ")
        },
    })

  }
}
0 Answers
Related