typescript
59 lines · 7 steps
Decoupling side effects with NestJS events
Placing an order emits a single event, letting inventory, email, and logging react independently without the service knowing about them.
Explained by
highlit
1import { Injectable, NotFoundException } from '@nestjs/common';
2import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
3import { InjectRepository } from '@nestjs/typeorm';
4import { Repository } from 'typeorm';
5import { Order } from './order.entity';
6import { MailerService } from '../mailer/mailer.service';
7import { InventoryService } from '../inventory/inventory.service';
8
9export class OrderPlacedEvent {
10 constructor(
11 public readonly orderId: string,
12 public readonly customerEmail: string,
13 public readonly items: { sku: string; quantity: number }[],
14 ) {}
15}
16
17@Injectable()
18export class OrdersService {
19 constructor(
20 @InjectRepository(Order) private readonly orders: Repository<Order>,
21 private readonly eventEmitter: EventEmitter2,
22 ) {}
23
24 async placeOrder(customerEmail: string, items: { sku: string; quantity: number }[]) {
25 const order = await this.orders.save(
26 this.orders.create({ customerEmail, items, status: 'pending' }),
27 );
28
29 this.eventEmitter.emit(
30 'order.placed',
31 new OrderPlacedEvent(order.id, customerEmail, items),
32 );
33
34 return order;
35 }
36}
37
38@Injectable()
39export class OrderNotificationsListener {
40 constructor(
41 private readonly mailer: MailerService,
42 private readonly inventory: InventoryService,
43 ) {}
44
45 @OnEvent('order.placed', { async: true })
46 async onOrderPlaced(event: OrderPlacedEvent) {
47 await this.inventory.reserve(event.items);
48 await this.mailer.send({
49 to: event.customerEmail,
50 template: 'order-confirmation',
51 context: { orderId: event.orderId },
52 });
53 }
54
55 @OnEvent('order.*')
56 logOrderActivity(event: OrderPlacedEvent) {
57 console.log(`[orders] activity for ${event.orderId}`);
58 }
59}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Emitting a domain event keeps the core write path unaware of downstream consumers, so adding reactions never touches the service.
- 2A typed event class carries exactly the data listeners need, avoiding refetches and keeping handlers self-contained.
- 3Wildcard subscriptions let cross-cutting concerns like logging hook into whole families of events at once.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/decoupling-side-effects-with-nestjs-events-explained-typescript-00cd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.