0
0
NestJSframework~10 mins

Event patterns (event-based) in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Event patterns (event-based)
Event Emitted
Event Bus Receives
Event Pattern Matches?
NoIgnore Event
Yes
Invoke Event Handler
Handler Processes Event
Optional: Emit New Event
Back to Event Bus
This flow shows how an event is emitted, matched by pattern, handled, and optionally triggers new events.
Execution Sample
NestJS
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';

export class UserCreatedEvent {
  constructor(public readonly userId: string) {}
}

@EventsHandler(UserCreatedEvent)
export class UserCreatedHandler implements IEventHandler<UserCreatedEvent> {
  handle(event: UserCreatedEvent) {
    console.log(`User created: ${event.userId}`);
  }
}
This code defines an event and a handler that listens for that event and logs the user ID.
Execution Table
StepActionEvent Bus StateEvent Pattern MatchHandler CalledOutput
1UserCreatedEvent emitted with userId='abc123'Event queue: [UserCreatedEvent]Matches UserCreatedEvent patternUserCreatedHandler.handle calledLogs: 'User created: abc123'
2Handler finishes processingEvent queue: []N/AN/ANo further output
3No more eventsEvent queue: []N/AN/AExecution stops
💡 No more events in the queue, event processing ends
Variable Tracker
VariableStartAfter Step 1After Step 2Final
eventQueue[][UserCreatedEvent][][]
currentEventnullUserCreatedEvent(userId='abc123')nullnull
Key Moments - 2 Insights
Why does the handler only run when the event pattern matches?
Because the event bus checks each event against registered patterns and only calls handlers for matching events, as shown in execution_table step 1.
What happens if no handler matches an event?
The event is ignored and removed from the queue without calling any handler, as implied by the 'No more events' step in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the eventQueue after step 1?
A[UserCreatedEvent]
B[]
C[UserCreatedEvent, AnotherEvent]
Dnull
💡 Hint
Check the 'Event Bus State' column at step 1 in the execution_table
At which step does the handler log the user ID?
AStep 3
BStep 1
CStep 2
DNo logging occurs
💡 Hint
Look at the 'Output' column for when 'Logs: User created: abc123' appears
If a new event with no matching handler is emitted, what happens to the eventQueue?
AIt stays the same
BIt grows indefinitely
CThe event is removed without handler call
DThe system crashes
💡 Hint
Refer to key_moments about unmatched events and execution_table step 3
Concept Snapshot
Event patterns in NestJS use an event bus to listen for specific event classes.
Handlers are registered with @EventsHandler for those event classes.
When an event is emitted, the bus matches it to handlers by pattern.
Matching handlers run their handle() method with the event data.
Unmatched events are ignored.
Handlers can emit new events, continuing the cycle.
Full Transcript
In NestJS event patterns, an event is created as a class and emitted to the event bus. The bus holds events in a queue. It checks each event against registered patterns, which are event classes linked to handlers. If the event matches a pattern, the corresponding handler's handle() method runs, processing the event data. For example, a UserCreatedEvent with a userId is emitted, matched, and handled by UserCreatedHandler, which logs the userId. After handling, the event is removed from the queue. If no handler matches, the event is simply discarded. This cycle allows decoupled communication where events trigger actions without direct calls. Handlers can also emit new events, continuing the event flow.