- Published
- Author
- Puneeth kumarSystem Analyst
Using
In NestJS, event-based communication can be implemented using
How to use it?
β’ Install the necessary package:
β’ Register the module in the app:
β’ Emit an event from anywhere in the app:
β’ Handle the event using a listener:
Why use emits?
β Decouples the core logic from side-effects
β Makes it easier to add/remove behaviours like notifications, logging
β Encourages modular architecture
#CCT1JMA0Z #nestJs #event_based_communication
emit in NestJSIn NestJS, event-based communication can be implemented using
@nestjs/event-emitter package, which is built on top of eventemitter2 . It's particularly useful for decoupling the parts of our application β for example, sending notifications, logging, or triggering async jobs after certain actions.How to use it?
β’ Install the necessary package:
Code
npm install --save @nestjs/event-emitterβ’ Register the module in the app:
Code
// app.module.ts
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [
EventEmitterModule.forRoot(),
],
})
export class AppModule {}β’ Emit an event from anywhere in the app:
Code
// user.service.ts
import { EventEmitter2 } from '@nestjs/event-emitter';
@Injectable()
export class UserService {
constructor(private eventEmitter: EventEmitter2) {}
async createUser(userDto: CreateUserDto) {
const user = await this.userRepository.save(userDto);
this.eventEmitter.emit('user.created', user); // π₯
return user;
}
}β’ Handle the event using a listener:
Code
// user.listener.ts
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class UserListener {
@OnEvent('user.created')
handleUserCreatedEvent(payload: any) {
console.log('User created!', payload);
// Trigger welcome email, analytics, etc.
}
}Why use emits?
β Decouples the core logic from side-effects
β Makes it easier to add/remove behaviours like notifications, logging
β Encourages modular architecture
#CCT1JMA0Z #nestJs #event_based_communication