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.
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.
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.
Practice
(1/5)
1. What is the main purpose of event handling in a NestJS application?
easy
A. To allow different parts of the app to react to actions without being tightly connected
B. To directly call methods from other classes
C. To replace all HTTP requests with events
D. To store data permanently in the database
Solution
Step 1: Understand event handling concept
Event handling lets parts of an app respond to actions independently, avoiding tight coupling.
Step 2: Compare options
Only To allow different parts of the app to react to actions without being tightly connected describes this purpose correctly; others describe unrelated concepts.
Final Answer:
To allow different parts of the app to react to actions without being tightly connected -> Option A
Quick Check:
Event handling = loose coupling reaction [OK]
Hint: Event handling means reacting without tight connections [OK]
Common Mistakes:
Thinking event handling replaces HTTP requests
Confusing event handling with direct method calls
Assuming event handling stores data
2. Which decorator is used to mark a class as an event handler in NestJS?
easy
A. @HandleEvent
B. @EventListener
C. @EventsHandler
D. @EventSubscriber
Solution
Step 1: Recall NestJS event handler syntax
The correct decorator to mark event handler classes is @EventsHandler.
Step 2: Verify options
Options B, C, and D are not valid NestJS decorators for event handlers.
Final Answer:
@EventsHandler -> Option C
Quick Check:
@EventsHandler marks event handlers [OK]
Hint: Use @EventsHandler to mark event handler classes [OK]
Common Mistakes:
Using @EventListener which is not a NestJS decorator
Confusing with @HandleEvent which does not exist
Using @EventSubscriber which is from other frameworks
3. Given this event handler code, what will be logged when eventBus.publish(new UserCreatedEvent('Alice')) is called?
A. The handle method is missing the event parameter
B. The @EventsHandler decorator is used incorrectly
C. The event class should not have a constructor
D. The console.log syntax is invalid
Solution
Step 1: Check handle method signature
The handle method must accept the event parameter to access event data.
Step 2: Identify usage of event data
Inside handle, orderId is used but not defined because event parameter is missing.
Final Answer:
The handle method is missing the event parameter -> Option A
Quick Check:
handle(event) needs event parameter [OK]
Hint: handle() must receive event parameter to access data [OK]
Common Mistakes:
Omitting event parameter in handle method
Misusing @EventsHandler decorator
Thinking constructor is not needed in event class
5. You want to handle two different events, UserCreatedEvent and UserDeletedEvent, in one handler class. Which approach correctly implements this in NestJS?
hard
A. Use @EventsHandler without parameters and check event type inside handle method
B. Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks
C. Use @EventsHandler on one class but implement two separate handle methods named handleUserCreated and handleUserDeleted
D. Create two separate handler classes each with @EventsHandler for one event
Solution
Step 1: Understand multiple event handling in one class
In NestJS, you can pass multiple event classes to @EventsHandler decorator on one class.
Step 2: Implement single handle method with event type checks
The handle method receives any event instance; inside it, you check the event type to handle accordingly.
Final Answer:
Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks -> Option B
Quick Check:
Multiple events in one handler use @EventsHandler(...events) [OK]
Hint: Use @EventsHandler with multiple events and one handle method [OK]
Common Mistakes:
Trying to define multiple handle methods in one class
Creating separate classes instead of one combined handler
Using @EventsHandler without parameters
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.