|
| 1 | +### Events |
| 2 | + |
| 3 | +[Event Emitter](https://www.npmjs.com/package/@nestjs/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. |
| 4 | + |
| 5 | +`EventEmitterModule` internally uses the [eventemitter2](https://github.com/EventEmitter2/EventEmitter2) package. |
| 6 | + |
| 7 | +#### Getting started |
| 8 | + |
| 9 | +First install the required package: |
| 10 | + |
| 11 | +```shell |
| 12 | +$ npm i --save @nestjs/event-emitter |
| 13 | +``` |
| 14 | + |
| 15 | +Once the installation is complete, import the `EventEmitterModule` into the root `AppModule` and run the `forRoot()` static method as shown below: |
| 16 | + |
| 17 | +```typescript |
| 18 | +@@filename(app.module) |
| 19 | +import { Module } from '@nestjs/common'; |
| 20 | +import { EventEmitterModule } from '@nestjs/event-emitter'; |
| 21 | + |
| 22 | +@Module({ |
| 23 | + imports: [ |
| 24 | + EventEmitterModule.forRoot() |
| 25 | + ], |
| 26 | +}) |
| 27 | +export class AppModule {} |
| 28 | +``` |
| 29 | + |
| 30 | +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. |
| 31 | + |
| 32 | +To configure the underlying `EventEmitter` instance, pass the configuration object to the `.forRoot()` method, as follows: |
| 33 | + |
| 34 | +```typescript |
| 35 | +EventEmitterModule.forRoot({ |
| 36 | + // set this to `true` to use wildcards |
| 37 | + wildcard: false, |
| 38 | + // the delimiter used to segment namespaces |
| 39 | + delimiter: '.', |
| 40 | + // set this to `true` if you want to emit the newListener event |
| 41 | + newListener: false, |
| 42 | + // set this to `true` if you want to emit the removeListener event |
| 43 | + removeListener: false, |
| 44 | + // the maximum amount of listeners that can be assigned to an event |
| 45 | + maxListeners: 10, |
| 46 | + // show event name in memory leak message when more than maximum amount of listeners is assigned |
| 47 | + verboseMemoryLeak: false, |
| 48 | + // disable throwing uncaughtException if an error event is emitted and it has no listeners |
| 49 | + ignoreErrors: false, |
| 50 | +}); |
| 51 | +``` |
| 52 | + |
| 53 | +#### Event listeners |
| 54 | + |
| 55 | +To declare an event listener, decorate a method with the `@OnEvent()` decorator preceding the method definition containing the code to be executed, as follows: |
| 56 | + |
| 57 | +```typescript |
| 58 | +@OnEvent('order.created') |
| 59 | +handleOrderCreatedEvent(payload: OrderCreatedEvent) { |
| 60 | + // handle and process "OrderCreatedEvent" event |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +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](https://github.com/EventEmitter2/EventEmitter2#emitteronevent-listener-options-objectboolean)). |
| 65 | + |
| 66 | +```typescript |
| 67 | +@OnEvent('order.created', { async: true }) |
| 68 | +handleOrderCreatedEvent(payload: OrderCreatedEvent) { |
| 69 | + // handle and process "OrderCreatedEvent" event |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +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: |
| 74 | + |
| 75 | +```typescript |
| 76 | +@OnEvent('order.*') |
| 77 | +handleOrderEvents(payload: OrderCreatedEvent | OrderRemovedEvent | OrderUpdatedEvent) { |
| 78 | + // handle and process an event |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +#### Dispatching events |
| 83 | + |
| 84 | +To dispatch an event, first inject `EventEmitter2` using standard constructor injection: |
| 85 | + |
| 86 | +```typescript |
| 87 | +constructor(private eventEmitter: EventEmitter2) {} |
| 88 | +``` |
| 89 | + |
| 90 | +> info **Hint** Import the `EventEmitter2` from the `@nestjs/event-emitter` package. |
| 91 | +
|
| 92 | +Then use it in a class as follows. |
| 93 | + |
| 94 | +```typescript |
| 95 | +this.eventEmitter.emit( |
| 96 | + 'order.created', |
| 97 | + new OrderCreatedEvent({ |
| 98 | + orderId: 1, |
| 99 | + payload: {}, |
| 100 | + }), |
| 101 | +); |
| 102 | +``` |
| 103 | + |
| 104 | +> info **Hint** `EventEmitter2` class provides several useful methods for interacting with events, like `waitFor` and `onAny`. You can read more about them [here](https://github.com/EventEmitter2/EventEmitter2). |
0 commit comments