Complete the code to create an event handler using the correct decorator.
import { Controller } from '@nestjs/common'; import { EventPattern } from '@nestjs/microservices'; @Controller() export class AppController { @[1]('order_created') handleOrderCreated(data: any) { console.log('Order created event received:', data); } }
The @EventPattern decorator is used in NestJS to listen for specific events in event-based communication.
Complete the code to emit an event named 'user_registered' with user data.
import { ClientProxy } from '@nestjs/microservices'; export class UserService { constructor(private client: ClientProxy) {} registerUser(user: any) { // user registration logic this.client.[1]('user_registered', user); } }
The emit method on ClientProxy is used to send events to the event bus in NestJS.
Fix the error in the event handler method signature to properly receive event data.
import { Controller } from '@nestjs/common'; import { EventPattern } from '@nestjs/microservices'; @Controller() export class PaymentController { @EventPattern('payment_processed') handlePayment([1]) { console.log('Payment processed:', data); } }
The event handler method should receive the event data as a parameter, commonly named data.
Fill both blanks to create a service that listens to 'inventory_updated' events and logs the update.
import { Injectable } from '@nestjs/common'; import { [1] } from '@nestjs/microservices'; @Injectable() export class InventoryService { @[2]('inventory_updated') handleInventoryUpdate(update: any) { console.log('Inventory updated:', update); } }
Both the import and the decorator should be EventPattern to listen to event-based messages.
Fill all three blanks to create a client service that emits 'notification_sent' events with a message payload.
import { Injectable } from '@nestjs/common'; import { [1] } from '@nestjs/microservices'; @Injectable() export class NotificationService { constructor(private client: [2]) {} sendNotification(message: string) { this.client.[3]('notification_sent', { message }); } }
The ClientProxy is imported and injected to emit events using the emit method.