Skip to content

NestJS : How to emit an event

Mathieu edited this page Jun 15, 2022 · 7 revisions

Before triggering an event, we suggest you read this article : NestJs Event - Event Emitter package.

Emit

EventEmitter2 is used to emit and listen to an event. It's possible to see code production samples inside the products.service.ts.

For example, after the creation of a product, the line bellow is used:

this.eventEmitter.emit('product.created', product);

This emit product.created means than a product has been created.

Event emited type

Type Describe Note
product.created A product has been created
product.retrieve A product has been retrieved by someone
product.warranty.extend An product's warranty has been extended
product.status.update A product's status has been updated
commercial.event A commercial event has been emited

Listener

The listener will read the event emited and create an event object on the database and the blockchain. This event will have an event type

Example :

//Handle and process on created
@OnEvent('product.created')
handleCreatedEvent(product) {
const event = {
  content: 'A product has been created',
  type: 'PRODUCT_CREATED',
};
this.saveEventOnDataBase(event, product);
this.saveEventOnBlockchain(event, product);
}

You may have noticed that an event type and an event emited type have common names. It's because the event emited type will trigger the creation of an event that contains an event and a product object.

Clone this wiki locally