📖 Scenario: You are building a simple NestJS application that listens for user registration events and processes them.This is like a mailroom receiving packages: when a new package (event) arrives, the mailroom (your app) handles it accordingly.
🎯 Goal: Create a NestJS event-based system where a UserRegistered event is defined, a listener subscribes to it, and the event is emitted to trigger the listener.
📋 What You'll Learn
Define an event pattern called UserRegistered
Create an event listener method that listens for UserRegistered events
Emit a UserRegistered event with a payload containing username and email
Use NestJS event-based patterns with @EventPattern and ClientProxy
💡 Why This Matters
🌍 Real World
Event-based communication is common in microservices and distributed systems to decouple components and react to changes asynchronously.
💼 Career
Understanding event patterns in NestJS is valuable for backend developers working with scalable, event-driven architectures.
Progress0 / 4 steps
1
Create the event pattern and payload interface
Create an interface called UserRegisteredEvent with username and email as string properties. Then define a constant USER_REGISTERED_EVENT with the value 'user_registered'.
NestJS
Hint
Think of the event as a message with a name and data. The interface describes the data shape.
2
Create an event listener method with @EventPattern
In a NestJS service class, create a method called handleUserRegistered decorated with @EventPattern(USER_REGISTERED_EVENT). The method should accept a parameter payload of type UserRegisteredEvent.
NestJS
Hint
The @EventPattern decorator listens for events with the given name.
3
Inject ClientProxy and emit the event
In a NestJS service class called UserService, inject ClientProxy named client via the constructor. Create a method registerUser that accepts username and email strings, then emits the USER_REGISTERED_EVENT with a payload matching UserRegisteredEvent.
NestJS
Hint
Use this.client.emit(eventName, payload) to send events.
4
Complete the event handling logic
Inside the handleUserRegistered method, add a line to log the message User registered: {username} ({email}) using the payload data with a template string.
NestJS
Hint
Use a template string with backticks to include variables inside the log message.
Practice
(1/5)
1. What is the main purpose of using @EventPattern in a NestJS application?
easy
A. To create database entities
B. To define HTTP routes for REST APIs
C. To listen for specific events and handle their data
D. To style components with CSS
Solution
Step 1: Understand the role of @EventPattern
This decorator is used to mark a method that listens for a specific event in an event-based system.
Step 2: Compare with other options
Options B, C, and D relate to other parts of NestJS or frontend development, not event listening.
Final Answer:
To listen for specific events and handle their data -> Option C
Quick Check:
@EventPattern listens to events [OK]
Hint: Remember: @EventPattern listens to events, not routes or styles [OK]
Common Mistakes:
Confusing @EventPattern with @Controller for routes
Thinking @EventPattern creates database models
Mixing event listening with styling tasks
2. Which of the following is the correct way to receive event data inside an event handler method in NestJS?
easy
A. Use @Payload() decorator on a method parameter
B. Use @Body() decorator on a method parameter
C. Use @Query() decorator on a method parameter
D. Use @Param() decorator on a method parameter
Solution
Step 1: Identify the decorator for event data
In NestJS event handlers, @Payload() extracts the data sent with the event.
Step 2: Differentiate from HTTP decorators
@Body(), @Query(), and @Param() are used in HTTP controllers, not event handlers.
Final Answer:
Use @Payload() decorator on a method parameter -> Option A
Quick Check:
@Payload() gets event data [OK]
Hint: Event data comes from @Payload(), not HTTP decorators [OK]
Common Mistakes:
Using @Body() in event handlers instead of @Payload()
Confusing HTTP request decorators with event decorators
Omitting the decorator and expecting automatic data injection
3. Given the following NestJS event handler code, what will be logged when an event named 'order_created' with payload { id: 42 } is emitted?
The @Payload decorator requires parentheses even if no arguments are passed, so it should be @Payload().
Step 2: Verify other parts
Event name format is correct, method name can be anything, and parameter order is flexible.
Final Answer:
Missing parentheses in @Payload decorator -> Option A
Quick Check:
@Payload() needs parentheses [OK]
Hint: Always write @Payload() with parentheses, even if empty [OK]
Common Mistakes:
Omitting parentheses in decorators
Thinking method names must follow event names
Assuming parameter order matters for decorators
5. You want to create a NestJS service that listens to two different events: 'payment_success' and 'payment_failed'. Which of the following is the best way to implement this using event patterns?
hard
A. Use @Controller with two routes named after events
B. Create two methods, each decorated with @EventPattern for each event name
C. Create one method with @EventPattern('payment') and check event type inside
D. Use @Payload() decorator twice in one method for both events
Solution
Step 1: Understand event pattern usage
Each event should have its own handler method decorated with @EventPattern specifying the event name.
Step 2: Evaluate other options
Create one method with @EventPattern('payment') and check event type inside is less clear and not idiomatic; Use @Controller with two routes named after events is for HTTP routes, not events; Use @Payload() decorator twice in one method for both events is invalid syntax.
Final Answer:
Create two methods, each decorated with @EventPattern for each event name -> Option B
Quick Check:
Separate methods for separate events [OK]
Hint: Use one @EventPattern per event with separate methods [OK]
Common Mistakes:
Trying to handle multiple events in one method without checking
Confusing event handlers with HTTP controllers
Using multiple @Payload decorators in one method
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.