I have a global dynamic module with a service named KafkaService, I want to use this service in my AuthenticationService, but NestJS seems can't inject the KafkaService
I have a KafkaModule which is a Dynamic and Global module
import { DynamicModule, Global, Module } from '@nestjs/common';
import { KafkaService } from './kafka.service';
import { KafkaConfig } from './kafka.types';
@Global()
@Module({})
export class KafkaModule {
static register(kafkaConfig: KafkaConfig): DynamicModule {
return {
module: KafkaModule,
global: true,
providers: [
{
provide: KafkaService,
useValue: new KafkaService(kafkaConfig),
},
],
exports: [KafkaService],
};
}
}
registered in AppModule
import { Module } from '@nestjs/common';
import { KafkaModule } from './common/kafka/kafka.module';
import { AuthenticationModule } from './modules/authentication.module';
@Module({
imports: [
KafkaModule.register({
clientId: 'abc',
brokers: ['localhost:9092'],
groupId: 'def',
}),
AuthenticationModule,
],
})
export class AppModule {}
I want to use it in my service
import { Injectable } from '@nestjs/common';
import { SubscribeTo } from 'src/common/kafka/kafka.decorator';
import { KafkaService } from 'src/common/kafka/kafka.service';
import { Constant } from 'src/constant';
type LoginPayload = {
username: string;
password: string;
};
@Injectable()
export class AuthenticationService {
constructor(private kafkaService: KafkaService) {}
@SubscribeTo(Constant.TOPIC_LOGIN)
async login(payload: LoginPayload) {
console.log(this.kafkaService);
}
}
UPDATE Apparently, the decorator is called before service injection
The decorator @SubscribeTo(Constant.TOPIC_LOGIN)
will save the function in a variable that will be called later, and when this decorator is run the service is not yet injected to the class
So, I'm not using decorator to subscribe to the topic, and then modifying the Kafka module so that the consumer will not start at module initialization