Events
DryerJS does not emit events by default.
However, you can easily add them by using a General Hook
combines with @nestjs/event-emitter
.
NestJS
document can be found here (opens in a new tab).
Installation
First you need to install @nestjs/event-emitter
:
npm i --save @nestjs/event-emitter
Implementation
Below example, we create a General Hook
to emit events when a record of any model is created, updated or removed.
Then there is a EmailService
that listens to the user.created
event and send a welcome email to the user.
import {
EventEmitter2,
EventEmitterModule,
OnEvent,
} from '@nestjs/event-emitter';
type Context = {};
@Injectable()
export class EventEmitterHook {
constructor(private readonly eventEmitter: EventEmitter2) {}
@AfterCreateHook(() => AllDefinitions)
async fireAfterCreateEvents(input: AfterCreateHookInput<any, Context>) {
this.eventEmitter.emit(`${input.definition.name}.created`, input);
}
@AfterUpdateHook(() => AllDefinitions)
async fireAfterUpdateEvents(input: AfterUpdateHookInput<any, Context>) {
this.eventEmitter.emit(`${input.definition.name}.updated`, input);
}
@AfterRemoveHook(() => AllDefinitions)
async fireAfterRemoveEvents(input: AfterRemoveHookInput<any, Context>) {
this.eventEmitter.emit(`${input.definition.name}.removed`, input);
}
}
@Injectable()
class EmailService {
@OnEvent('User.created')
async handleOrderCreatedEvent({
input,
}: AfterCreateHookInput<User, Context>) {
console.log(`Send welcome email to ${input.email}`);
}
}
@Module({
imports: [
// other imports
EventEmitterModule.forRoot(),
DryerModule.register({
definitions: [User],
providers: [EventEmitterHook],
}),
],
providers: [EmailService],
})
export class AppModule {}