yak0/nest-event

Cannot read property 'has' of undefined

Sairyss opened this issue · 2 comments

I am having issues using nest-event. I have NestEventModule imported in app.module

imports: [ NestEventModule, ... ]

Then I am injecting it in my service:
constructor(private nestEvent: NestEventEmitter)

And finally I emit an event:
this.nestEvent.emit('TESTEMIT');

This emit is triggered when I do a GET request to my API.

But all I get is this error:

error:   ┏ Cannot read property 'has' of undefined: +6ms
error:   ┃ [1] TypeError: Cannot read property 'has' of undefined
error:   ┃ [2]     at NestEventEmitter.emitter (/home/user/code/core/node_modules/nest-event/nest-event-emitter.js:42:42)
error:   ┃ [3]     at NestEventEmitter.emit (/home/user/code/core/node_modules/nest-event/nest-event-emitter.js:24:35)
error:   ┃ [4]     at UserService.test (/home/user/code/core/artifacts/dist/src/app/modules/user/services/user.service.js:45:24)
error:   ┃ [5]     at UserEventsController.readAll (/home/user/code/core/artifacts/dist/src/app/modules/user/controllers/user.events.controller.js:38:22)
error:   ┃ [6]     at /home/user/code/core/node_modules/@nestjs/microservices/context/rpc-context-creator.js:44:33
error:   ┗ [7]     at processTicksAndRejections (internal/process/task_queues.js:93:5)

It happens right here: if (!this.nestEvent.getEmitters().has(emitter)) {

I tried creating different emitter classes with @emitter() decorator but it doesn't help.
I also tried executing configure() method manually as I've seen in the code it is used for setting emitters in a Map, also doesn't help.

Any suggestions? Thanks in advance

Just tried it in a clean installed NestJS and it works. Seems that nest-event package is incompatible with something that I have in my project.

So this is the fix for me, i'll leave it here in case somebody else encounters the same problem.
To fix this, you need to execute configure() method manually inside main.ts file:

  const app = await NestFactory.create(AppModule) <-  nest creating your app
  ...
  await app.get(NestEventModule).configure(); <- this goes below after your app is created

As i said i tried to use it before, but it didn't work. The reason behind it was that I already had a node event emitter in my app, so when I replaced node emitter with nest-event in my provider, and executed configure() manually, everything started working.
Without executing configure() manually it still throws the same error though