Events
Incase, you want to use event package in your application (if you are not using this boilerplate), you can do so by install @squareboat/nest-events
package seperately.
npm i @squareboat/nest-events --save
This boilerplate provides out-of-the-box support for event listeners. It implements a simple observer pattern and allows to subscribe to multiple events that may occur in your application.
Incase you don't know about observer pattern, here is a good article to start with.
Events provide a great mechanism to decouple your business logic which do not depend on each other. Let's understand it better with the help of an example: Let's say you are building an application, when any of the new user signs up, you may want to do following things:
- Send welcome notification
- Add to marketing campaigns
- Add Signup Reward to wallet bonus, etc.
See how the above mentioned points, do not depend on each other, they can run independently and complete their own specified task. One way is to just write the logic all in one service, and inject every provider in the AuthService
. Another way, is to emit UserSignUp
event and listen to the UserSignUp
event and perform their assigned task.
As soon as the UserSignUp
event is triggered in the application, all the listeners will start.
Creating an Event
To create an event, you need to create a class decorated with @Event
decorator and extending EmitsEvent
class.
import { Event } from '@squareboat/nest-events';
@Event('USER_SIGNED_UP')
export class UserSignedUp extends EmitsEvent {}
@Event()
is the decorator where USER_SIGNED_UP
is the name of the events. Listeners will be listening to the event identified by their name.
Create Listener
To create a listener for the event, you need to use @EventListener
decorator.
import { Injectable } from '@nestjs/common';
import { ListensTo } from '@squareboat/nest-events';
import { UserSignedUp } from '../events/UserSignedUp';
@Injectable()
export class UserService {
@ListensTo('USER_SIGNED_UP')
userSignedUp(event: UserSignedUp): void {
console.log('EVENT RECEIVED ===>', event);
// add your logic here
return;
}
}
The @ListensTo
decorator will add the method as one of the subscriber for "USER_SIGNED_UP"
event.
EventListeners will always receive the instance of the event emitted.
Emit Event
To emit an event, simply create an instance of the event and call the emit
method. The method expects a payload to be passed in the event.
import { EmitEvent } from '@squareboat/nest-events';
EmitEvent(new UserSignedUp(), {name: 'Tony Stark', contactNumber: 'XXXXXXXXXX'});
In the listener, you will receive the instance of the UserSignedUp
event. To get the payload passed in the event, simply do:
import { ListensTo } from '@squareboat/nest-events';
@ListensTo('USER_SIGNED_UP')
userSignedUp(event: UserSignedUp): void {
const data = event.getData();
// add your logic here
return;
}