0
0
NestJSframework~5 mins

Event patterns (event-based) in NestJS

Choose your learning style9 modes available
Introduction

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.
NestJS
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';

@Controller()
export class UserController {
  @EventPattern('user_created')
  handleUserCreated(@Payload() userData: any) {
    console.log('User created:', userData);
  }
}
This listens for 'order_placed' events and processes orders asynchronously.
NestJS
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';

@Controller()
export class OrderController {
  @EventPattern('order_placed')
  async handleOrder(@Payload() orderData: any) {
    // process order asynchronously
  }
}
Sample Program

This simple controller listens for 'send_notification' events and prints a message to notify a user.

NestJS
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';

@Controller()
export class NotificationController {
  @EventPattern('send_notification')
  handleNotification(@Payload() message: { userId: string; text: string }) {
    console.log(`Notify user ${message.userId}: ${message.text}`);
  }
}
OutputSuccess
Important Notes

Event names should be clear and descriptive to avoid confusion.

Event handlers can be async if you need to do tasks like database calls.

Use event patterns to keep your app modular and easier to maintain.

Summary

Event patterns help parts of your app communicate by sending and receiving messages.

Use @EventPattern to listen for specific events and @Payload() to get event data.

This approach makes your app more organized and ready for complex tasks.