Events

Event Emitter package (@nestjs/event-emitter) provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.

EventEmitterModule internally uses the eventemitter2 package.

Getting started

First install the required package:

  1. $ npm i --save @nestjs/event-emitter

Once the installation is complete, import the EventEmitterModule into the root AppModule and run the forRoot() static method as shown below:

  1. @@filename(app.module)
  2. import { Module } from '@nestjs/common';
  3. import { EventEmitterModule } from '@nestjs/event-emitter';
  4. @Module({
  5. imports: [
  6. EventEmitterModule.forRoot()
  7. ],
  8. })
  9. export class AppModule {}

The .forRoot() call initializes the event emitter and registers any declarative event listeners that exist within your app. Registration occurs when the onApplicationBootstrap lifecycle hook occurs, ensuring that all modules have loaded and declared any scheduled jobs.

To configure the underlying EventEmitter instance, pass the configuration object to the .forRoot() method, as follows:

  1. EventEmitterModule.forRoot({
  2. // set this to `true` to use wildcards
  3. wildcard: false,
  4. // the delimiter used to segment namespaces
  5. delimiter: '.',
  6. // set this to `true` if you want to emit the newListener event
  7. newListener: false,
  8. // set this to `true` if you want to emit the removeListener event
  9. removeListener: false,
  10. // the maximum amount of listeners that can be assigned to an event
  11. maxListeners: 10,
  12. // show event name in memory leak message when more than maximum amount of listeners is assigned
  13. verboseMemoryLeak: false,
  14. // disable throwing uncaughtException if an error event is emitted and it has no listeners
  15. ignoreErrors: false,
  16. });

Dispatching Events

To dispatch (i.e., fire) an event, first inject EventEmitter2 using standard constructor injection:

  1. constructor(private eventEmitter: EventEmitter2) {}

info Hint Import the EventEmitter2 from the @nestjs/event-emitter package.

Then use it in a class as follows:

  1. this.eventEmitter.emit(
  2. 'order.created',
  3. new OrderCreatedEvent({
  4. orderId: 1,
  5. payload: {},
  6. }),
  7. );

Listening to Events

To declare an event listener, decorate a method with the @OnEvent() decorator preceding the method definition containing the code to be executed, as follows:

  1. @OnEvent('order.created')
  2. handleOrderCreatedEvent(payload: OrderCreatedEvent) {
  3. // handle and process "OrderCreatedEvent" event
  4. }

warning Warning Event subscribers cannot be request-scoped.

The first argument can be a string or symbol for a simple event emitter and a string | symbol | Array<string | symbol> in a case of a wildcard emitter. The second argument (optional) is a listener options object (read more).

  1. @OnEvent('order.created', { async: true })
  2. handleOrderCreatedEvent(payload: OrderCreatedEvent) {
  3. // handle and process "OrderCreatedEvent" event
  4. }

To use namespaces/wildcards, pass the wildcard option into the EventEmitterModule#forRoot() method. When namespaces/wildcards are enabled, events can either be strings (foo.bar) separated by a delimiter or arrays (['foo', 'bar']). The delimiter is also configurable as a configuration property (delimiter). With namespaces feature enabled, you can subscribe to events using a wildcard:

  1. @OnEvent('order.*')
  2. handleOrderEvents(payload: OrderCreatedEvent | OrderRemovedEvent | OrderUpdatedEvent) {
  3. // handle and process an event
  4. }

Note that such a wildcard only applies to one block. The argument order.* will match, for example, the events order.created and order.shipped but not order.delayed.out_of_stock. In order to listen to such events, use the multilevel wildcard pattern (i.e, **), described in the EventEmitter2 documentation.

With this pattern, you can, for example, create an event listener that catches all events.

  1. @OnEvent('**')
  2. handleEverything(payload: any) {
  3. // handle and process an event
  4. }

info Hint EventEmitter2 class provides several useful methods for interacting with events, like waitFor and onAny. You can read more about them here.

Example

A working example is available here.