DEV Community

loading...
Cover image for The Crazy decoupler - NestJs Emitter

The Crazy decoupler - NestJs Emitter

Visakh Vijayan
Willing to learn anything and everything exciting. Always awake. Skips food for fun.
Updated on ・1 min read

Those of us who have used NestJs are familiar of the architectural flow. We break code into modules. Modules have controller which are basically the public endpoints. And then there are services which can be injected on demand.

It gets messy when we have to communicate across modules. Sure if you are using micro-services it's a different game altogether, but there is something in NestJs which gives crazy level of decoupling. And those are called Event Emitters.

By using this guy, you can emit an event in a controller/service and listen for it in another controller/service WITHOUT importing them into each other. How cool is that. Wonder why we don't use it more often. Hmm!!! Need to read up on the cons of this stuff too I guess.

But till then, here is how simple it is.

THE EMITTER

@Get("emit")
async emit()
{
    this.EventEmitter.emit
    (
        'hello',
        "My name is Antony Gonzalves!"
    );  
}
Enter fullscreen mode Exit fullscreen mode

THE LISTENER

@OnEvent('hello')
handleOrderCreatedEvent(message) 
{
    console.log("I am expecting some messages now!");
    console.log(message);
}
Enter fullscreen mode Exit fullscreen mode

Points to note -

  1. The emitter and listener are two separate files - can be controllers or services - doesn't matter.
  2. The emitter basically emits an event called "hello" with data "My name is Antony Gonzalves!".
  3. The listener is waiting for an event "hello". As soon as it receives, it prints the message out.

Crazy simple.

Please comment on the cons of this approach if you guys know any.

Happy Programming !!!

Discussion (1)

Collapse
pierre_davy_eac16ea42cf69 profile image
pierre davy

The con of the pub/sub pattern to my pow is:

  • can add a level of difficulty to test
  • can end up on spaghetti code with dependancies not clearly stated