Event patterns let different parts of your app talk by sending and listening to messages. This helps your app stay organized and react to things happening.
When you want to separate parts of your app so they don't depend on each other directly.
When you need to react to actions happening somewhere else in your app, like a user signing up.
When you want to build features that work with messages from other services or microservices.
When you want to handle tasks asynchronously, like sending emails after a user registers.
Syntax
NestJS
import { Controller } from'@nestjs/common';
import { EventPattern, Payload } from'@nestjs/microservices';
@Controller()
export class MyController {
@EventPattern('event_name')
handleEvent(@Payload() data: any) {
// handle the event data
}
}
@EventPattern listens for events with a specific name.
@Payload() extracts the data sent with the event.
Examples
This listens for the 'user_created' event and logs the user data.
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.