Skip to content

Commit 00a94ad

Browse files
docs(): add events docs
1 parent 64d53dc commit 00a94ad

File tree

4 files changed

+121
-1
lines changed

4 files changed

+121
-1
lines changed

content/techniques/events.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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).

src/app/homepage/menu/menu.component.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ export class MenuComponent implements OnInit {
9292
{ title: 'Queues', path: '/techniques/queues' },
9393
{ title: 'Logging', path: '/techniques/logger' },
9494
{ title: 'Cookies', path: '/techniques/cookies' },
95-
// { title: 'Events', path: '/techniques/#' },
95+
{ title: 'Events', path: '/techniques/events' },
9696
{ title: 'Compression', path: '/techniques/compression' },
9797
{ title: 'File upload', path: '/techniques/file-upload' },
9898
{ title: 'HTTP module', path: '/techniques/http-module' },
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { ChangeDetectionStrategy, Component } from '@angular/core';
2+
import { BasePageComponent } from '../../page/page.component';
3+
4+
@Component({
5+
selector: 'app-events',
6+
templateUrl: './events.component.html',
7+
changeDetection: ChangeDetectionStrategy.OnPush,
8+
})
9+
export class EventsComponent extends BasePageComponent {}

src/app/homepage/pages/techniques/techniques.module.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { CachingComponent } from './caching/caching.component';
66
import { CompressionComponent } from './compression/compression.component';
77
import { ConfigurationComponent } from './configuration/configuration.component';
88
import { CookiesComponent } from './cookies/cookies.component';
9+
import { EventsComponent } from './events/events.component';
910
import { FileUploadComponent } from './file-upload/file-upload.component';
1011
import { HttpModuleComponent } from './http-module/http-module.component';
1112
import { LoggerComponent } from './logger/logger.component';
@@ -116,6 +117,11 @@ const routes: Routes = [
116117
component: ServerSentEventsComponent,
117118
data: { title: 'Server-Sent Events' },
118119
},
120+
{
121+
path: 'events',
122+
component: EventsComponent,
123+
data: { title: 'Events' },
124+
},
119125
];
120126

121127
@NgModule({
@@ -128,6 +134,7 @@ const routes: Routes = [
128134
LoggerComponent,
129135
TaskSchedulingComponent,
130136
PerformanceComponent,
137+
EventsComponent,
131138
FileUploadComponent,
132139
HttpModuleComponent,
133140
ConfigurationComponent,

0 commit comments

Comments
 (0)