Bird
Raised Fist0
NestJSframework~20 mins

Event patterns (event-based) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Event Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when an event is emitted?
Consider a NestJS event emitter setup where a listener logs a message when an event named 'user.created' is emitted. What will be logged when the event is emitted with payload { id: 42 }?
NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class UserService {
  constructor(private eventEmitter: EventEmitter2) {}

  createUser() {
    this.eventEmitter.emit('user.created', { id: 42 });
  }
}

@Injectable()
export class UserListener {
  @OnEvent('user.created')
  handleUserCreatedEvent(payload: { id: number }) {
    console.log(`User created with id: ${payload.id}`);
  }
}
ANo output, event not handled
BUser created with id: undefined
CUser created with id: 42
DError: EventEmitter2 is not defined
Attempts:
2 left
💡 Hint
Think about how the @OnEvent decorator works and what payload is passed to the listener.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines an event listener in NestJS?
You want to listen to an event named 'order.completed' in a NestJS service. Which code snippet correctly sets up the listener?
A
@OnEvent('order.completed')
handleOrderCompleted(payload: any) {
  console.log('Order completed:', payload);
}
B
@EventListener('order.completed')
handleOrderCompleted(payload: any) {
  console.log('Order completed:', payload);
}
C
@Subscribe('order.completed')
handleOrderCompleted(payload: any) {
  console.log('Order completed:', payload);
}
D
@ListenEvent('order.completed')
handleOrderCompleted(payload: any) {
  console.log('Order completed:', payload);
}
Attempts:
2 left
💡 Hint
Check the official NestJS event emitter decorator name.
🔧 Debug
advanced
2:30remaining
Why does the event listener not respond?
Given the following NestJS code, why does the listener not log anything when the event is emitted?
NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class NotificationService {
  constructor(private eventEmitter: EventEmitter2) {}

  sendNotification() {
    this.eventEmitter.emit('notification.sent', { message: 'Hello' });
  }
}

@Injectable()
export class NotificationListener {
  @OnEvent('notification.send')
  handleNotification(payload: { message: string }) {
    console.log('Notification:', payload.message);
  }
}
AThe event name in the listener ('notification.send') does not match the emitted event name ('notification.sent').
BThe listener method is missing the async keyword.
CEventEmitter2 is not injected properly in NotificationListener.
DThe payload type is incorrect and causes a runtime error.
Attempts:
2 left
💡 Hint
Check the event names carefully for exact matches.
❓ state_output
advanced
2:30remaining
What is the final state after emitting multiple events?
A NestJS service emits two events in sequence. A listener updates a count each time it receives the event. What is the final count after both events?
NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class CounterService {
  private count = 0;

  constructor(private eventEmitter: EventEmitter2) {}

  increment() {
    this.eventEmitter.emit('counter.increment');
  }

  getCount() {
    return this.count;
  }
}

@Injectable()
export class CounterListener {
  private count = 0;

  @OnEvent('counter.increment')
  handleIncrement() {
    this.count += 1;
  }

  getCount() {
    return this.count;
  }
}

// In application code:
// counterService.increment();
// counterService.increment();
// What is counterListener.getCount()?
A0
BError: count is private and inaccessible
C1
D2
Attempts:
2 left
💡 Hint
Events decouple the emitter and listener. The listener updates its own state independently each time the event is emitted.
🧠 Conceptual
expert
3:00remaining
Which statement best describes event propagation in NestJS event emitter?
In NestJS using EventEmitter2, what happens when multiple listeners are registered for the same event and one listener throws an error during event handling?
AListeners are called asynchronously; errors in one listener do not affect others, all listeners run regardless.
BAll listeners are called in order; if one throws an error, the error is propagated and remaining listeners are not called.
CListeners are called synchronously; if one throws an error, it is caught internally and logged, allowing others to run.
DOnly the first listener is called; if it throws an error, event propagation stops immediately.
Attempts:
2 left
💡 Hint
Think about synchronous event emission and error handling in EventEmitter2 by default.

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

  1. 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.
  2. Step 2: Compare with other options

    Options B, C, and D relate to other parts of NestJS or frontend development, not event listening.
  3. Final Answer:

    To listen for specific events and handle their data -> Option C
  4. 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

  1. Step 1: Identify the decorator for event data

    In NestJS event handlers, @Payload() extracts the data sent with the event.
  2. Step 2: Differentiate from HTTP decorators

    @Body(), @Query(), and @Param() are used in HTTP controllers, not event handlers.
  3. Final Answer:

    Use @Payload() decorator on a method parameter -> Option A
  4. 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?
@EventPattern('order_created')
handleOrder(@Payload() data: any) {
  console.log(`Order ID: ${data.id}`);
}
medium
A. No output because event name is wrong
B. Order ID: undefined
C. SyntaxError due to missing return
D. Order ID: 42

Solution

  1. Step 1: Understand event matching

    The handler listens for 'order_created' events, so it will trigger when such an event is emitted.
  2. Step 2: Check payload usage

    The payload has an object with id: 42, so data.id is 42 and will be logged.
  3. Final Answer:

    Order ID: 42 -> Option D
  4. Quick Check:

    Payload id 42 logs correctly [OK]
Hint: Match event name exactly and use @Payload() to access data [OK]
Common Mistakes:
  • Assuming event name is case-insensitive
  • Forgetting to use @Payload() and getting undefined
  • Expecting a return value to log output
4. Identify the error in this NestJS event handler code:
@EventPattern('user_registered')
handleUser(@Payload data: any) {
  console.log(data.username);
}
medium
A. Missing parentheses in @Payload decorator
B. Incorrect event name format
C. Method name must be 'onUserRegistered'
D. Payload parameter must be last in method

Solution

  1. Step 1: Check decorator syntax

    The @Payload decorator requires parentheses even if no arguments are passed, so it should be @Payload().
  2. Step 2: Verify other parts

    Event name format is correct, method name can be anything, and parameter order is flexible.
  3. Final Answer:

    Missing parentheses in @Payload decorator -> Option A
  4. 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

  1. Step 1: Understand event pattern usage

    Each event should have its own handler method decorated with @EventPattern specifying the event name.
  2. 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.
  3. Final Answer:

    Create two methods, each decorated with @EventPattern for each event name -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard