Search code examples
nestjseventemitter

Event Emitter gets emmited multiple times , Nest JS


I am new to Event Emitters and tried implementing them in my Nest JS project, the problem is that the same event gets triggered multiple times (6 times to be exact) , any reason as to why and how to resolve this ?

This is the code snippet in the service.ts file to emit the event. this.eventEmitter.emit('company.created', companyCreatedHistory);

This is my Event , in the listener.ts file

@Injectable()
export class EntityCreatedListener {
  constructor(private readonly historyService: HistoriesService) {}

  @OnEvent('company.created')
  handleCompanyCreatedEvent(eventObject: typeof eventEmitterObject) {
    console.log('Hi')
    this.createAuditLog(eventObject, 'company.created');
  }

Referred from : https://github.com/nestjs/nest/tree/master/sample/30-event-emitter https://www.npmjs.com/package/@nestjs/event-emitter


Solution

  • So looking at your code I am guessing the problem is because you have different instances of the EntityCreatedListener flying around in your application. You probably have instantiated it 6 times that's why the event is firing 6 times.

    All these instances of the EntityCreatedListener will be listening for the company.created event and will fire once this method call this.eventEmitter.emit('company.created', companyCreatedHistory); triggers the event.

    THE FIX WOULD BE: Check the modules in your application and make sure the EntityCreatedListener is not imported in multiple places in the provider imports on this section of the module code @Module({imports: [],controllers: [],providers: []}). Keep only one instance of the EntityCreatedListener (thus it should be imported in only one module and shared to other modules by exporting it if you want to use in multiple places)