What is event-driven architecture in NestJS using the EventEmitter?
Answer
NestJS provides the @nestjs/event-emitter module for event-driven patterns within a single application (not between microservices). Import EventEmitterModule.forRoot(). Emit events: this.eventEmitter.emit('user.created', new UserCreatedEvent(user)). Listen with: @OnEvent('user.created') handleUserCreated(payload: UserCreatedEvent) { ... }. The @OnEvent() decorator registers the method as an event handler. Events are dispatched synchronously by default; use EventEmitterModule.forRoot({ global: true, async: true }) for async dispatch. This pattern decouples side effects (sending welcome emails, updating caches) from the primary operation (creating a user), enabling the single-responsibility principle without introducing a full message broker for intra-service communication.
Previous
How do you implement caching in NestJS?
Next
How do you handle database transactions in NestJS with TypeORM?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?