@byal-boilerplate/event-emitter
v0.0.1
Published
This library can be used to send and handle events. It provides an abstraction of a message queue provider like RabbitMQ or Redis.
Downloads
70
Readme
Event Emitter
This library can be used to send and handle events. It provides an abstraction of a message queue provider like RabbitMQ or Redis.
Usage
Import the module
import { Module } from '@nestjs/common';
import { EventEmitter } from '@byal-boilerplate/event-emitter';
import { env } from '../config/env';
@Module({
imports: [
EventEmitterModule.forRoot({ queuePrefix: env.APPLICATION_SLUG_NAME }),
],
controllers: [],
providers: [],
})
export class AppModule {}
When the API import this library module, it will search for the handlers declared by the @Subscriber()
decorator. The handlers will be registered in the event emitter and will be called when an event is received.
Sending events
After importing the module, the event emitter can be injected into a service and used to send events.
import { EventEmitter, TestEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(private readonly eventEmitter: EventEmitter) {}
async sendEvent() {
await this.eventEmitter.send(TestEvent, {
email: '[email protected]',
});
}
}
Decorators
@Subscriber(EventType)
This decorator can be used to register a handler for an event. It should be used only in a provider method.
This decorator has one parameter, the event type. The event type must be a class that extends the BaseEvent
abstract class and decorated with @RoutingKey()
. Next, an example of a subscriber:
import { Subscribe, TestEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
@Subscribe(TestEvent)
handleTestEvent(event: TestEvent) {
this.logger.debug(`Message received: ${event.payload}`);
}
}
Each application can have only one handler for each event type. If more than one handler is registered for the same event type, an error will be thrown when the application starts, but the application will continue to run using only the first handler registered.
@RoutingKey('exemple.event')
This decorator can be used to define the routing key of an event. It should be used only in a class that extends the BaseEvent
abstract class and inside this library. All contracts events declared in this library are already decorated with this decorator.
import { RoutingKey } from '../../decorators/routing-key.decorator';
import { BaseEvent } from '../base-event';
interface UserCreatedPayload {
id: string;
name: string;
}
@RoutingKey('user.created')
export class UserCreatedEvent extends BaseEvent<UserCreatedPayload> {}
Create a new event
To create a new event, you must run the generate command:
nx generate @byal-boilerplate/event-emitter:event
This command will ask you for the following information:
- Project: The project that is the owner of the event.
- Event name: The name of the event. This name will be used to create the event file and class name.
- Routing key: The routing key of the event. This key will be used to identify the event in the message queue.
- Description: A description of the event.
For example, if you want to create an event called UserUpdated
, you must run the following command:
nx generate @byal-boilerplate/event-emitter:event --dryRun
> NX Generating @byal-boilerplate/event-emitter:event
✔ Which project is the owner of this event · auth-api
✔ What is the name of the event in `kebab-case` · user-updated
✔ What is the event routing key · user.updated
✔ What is the event description · Emitted when an user has changed
The command will return the following output with the created and updated files:
CREATE libs/event-emitter/src/lib/contracts/auth-api/user-updated.ts
UPDATE libs/event-emitter/src/lib/contracts/index.ts
It means that the event file was created in the contracts
folder and the index.ts
file was updated to export the new event. Now you can use the new event in your application.
Send the event
import { EventEmitter, UserUpdatedEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(private readonly eventEmitter: EventEmitter) {}
async sendEvent() {
await this.eventEmitter.send(UserUpdatedEvent, {
id: 'user-id-123',
});
}
}
Handle the event
import { Subscribe, UserUpdatedEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
@Subscribe(UserUpdatedEvent)
handleUserUpdatedEvent(event: UserUpdatedEvent) {
this.logger.debug(`Message received: ${event.payload}`);
}
}