The Crazy decoupler - NestJs Emitter

Visakh Vijayan - May 12 '21 - - Dev Community

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 !!!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .