Event handling lets your app react to actions or changes by running specific code. It helps parts of your app talk to each other without being tightly connected.
0
0
Event handling in NestJS
Introduction
When you want to run code after a user signs up, like sending a welcome email.
When different parts of your app need to update after a change, like refreshing data.
When you want to keep your code organized by separating actions from reactions.
When you want to handle errors or logs in a centralized way.
When you want to trigger background tasks without blocking the main process.
Syntax
NestJS
import { EventsHandler, IEventHandler } from '@nestjs/cqrs'; @EventsHandler(EventClass) export class EventHandlerClass implements IEventHandler<EventClass> { handle(event: EventClass) { // code to run when event happens } }
Use @EventsHandler decorator to mark a class as an event handler.
The handle method runs automatically when the event is published.
Examples
This example shows an event for when a user is created and a handler that sends a welcome email.
NestJS
export class UserCreatedEvent { constructor(public readonly userId: string) {} } @EventsHandler(UserCreatedEvent) export class SendWelcomeEmailHandler implements IEventHandler<UserCreatedEvent> { handle(event: UserCreatedEvent) { console.log(`Send email to user ${event.userId}`); } }
This shows how to publish (trigger) an event so handlers can react.
NestJS
import { EventBus } from '@nestjs/cqrs'; constructor(private eventBus: EventBus) {} this.eventBus.publish(new UserCreatedEvent('123'));
Sample Program
This complete example shows how to define an event, create a handler that logs a message, and publish the event when placing an order.
NestJS
import { Injectable } from '@nestjs/common'; import { EventsHandler, IEventHandler, EventBus, CqrsModule } from '@nestjs/cqrs'; import { Module } from '@nestjs/common'; // Define an event export class OrderPlacedEvent { constructor(public readonly orderId: string) {} } // Create an event handler @EventsHandler(OrderPlacedEvent) export class NotifyWarehouseHandler implements IEventHandler<OrderPlacedEvent> { handle(event: OrderPlacedEvent) { console.log(`Notify warehouse about order ${event.orderId}`); } } @Injectable() export class OrderService { constructor(private eventBus: EventBus) {} placeOrder(orderId: string) { // Imagine order logic here this.eventBus.publish(new OrderPlacedEvent(orderId)); } } @Module({ imports: [CqrsModule], providers: [OrderService, NotifyWarehouseHandler], }) export class AppModule {} // Simulate running the code async function main() { const eventBus = new EventBus(); const handler = new NotifyWarehouseHandler(); eventBus.register([handler]); const orderService = new OrderService(eventBus); orderService.placeOrder('A100'); } main();
OutputSuccess
Important Notes
Remember to register your event handlers with the EventBus so they can listen to events.
Events help keep your code clean by separating what happens from when it happens.
Summary
Event handling lets parts of your app react to actions without tight connections.
Use @EventsHandler and handle method to create handlers.
Publish events with eventBus.publish() to trigger handlers.