0Pricing
NestJS Enterprise Backend APIs · 강의

도메인 이벤트와 AggregateRoot

EventBus와 mergeObjectContext를 사용해 애그리게이트 루트에서 도메인 이벤트를 발생시키고 발행합니다.

도메인 이벤트와 AggregateRoot은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Domain Events?

In an event-driven CQRS system, a domain event records something meaningful that already happened inside your domain: OrderPlaced, PaymentCaptured, UserDeactivated. They are named in the past tense because they are facts, not requests.

Domain events let you decouple side effects from the core write logic. Instead of an order service directly calling email, inventory, and analytics code, it simply emits OrderPlaced, and independent handlers react.

  • Command: an intent to change state (PlaceOrderCommand).
  • Event: a record of a change that occurred (OrderPlacedEvent).

NestJS provides first-class support for this through @nestjs/cqrs, the AggregateRoot base class, and the EventBus.

The AggregateRoot Base Class

An aggregate root is the entry point to a cluster of domain objects that change together and must stay consistent. In @nestjs/cqrs, you make a class an aggregate by extending AggregateRoot.

This base class gives you two key methods:

  • apply(event) — record a domain event that happened in this aggregate.
  • commit() — publish all recorded events to the EventBus.

The aggregate buffers events internally until you explicitly commit them. This separation lets you mutate state first and publish only after the change is safely persisted.

import { AggregateRoot } from '@nestjs/cqrs';

export class OrderPlacedEvent {
  constructor(
    public readonly orderId: string,
    public readonly total: number,
  ) {}
}

export class Order extends AggregateRoot {
  constructor(public readonly id: string) {
    super();
  }

  place(total: number) {
    // mutate state here, then record the fact
    this.apply(new OrderPlacedEvent(this.id, total));
  }
}

apply() Buffers, commit() Publishes

When you call this.apply(event), the event is pushed onto an internal array on the aggregate. Nothing is published yet.

Only when you call aggregate.commit() does NestJS iterate that buffer and hand each event to the publisher, which forwards them to the EventBus for handlers to consume.

This two-phase flow is intentional:

  • You can apply several events during one operation.
  • You persist the new state to the database.
  • Then you commit so events fire after a successful save, avoiding side effects on a transaction that later rolls back.

The Missing Publisher Problem

There is a catch. If you simply new Order(...) in a command handler and call commit(), nothing happens. The aggregate has no reference to the real EventBus — its default publisher is a no-op.

The aggregate must be wired to a publisher that knows how to push events onto the bus. That wiring is exactly what EventPublisher.mergeObjectContext (and mergeClassContext) provides.

Forgetting this step is the single most common reason newcomers report that their domain events "never fire" in NestJS CQRS.

mergeObjectContext: Wiring the EventBus

EventPublisher.mergeObjectContext(aggregate) takes an existing aggregate instance and injects the real publisher into it, so that a later commit() actually dispatches events to the EventBus.

Use it inside a command handler:

  • Build or load your aggregate.
  • Wrap it: const order = this.publisher.mergeObjectContext(rawOrder).
  • Run domain behavior (which calls apply internally).
  • Persist, then call order.commit().

Inject EventPublisher from @nestjs/cqrs through the constructor.

import { CommandHandler, ICommandHandler, EventPublisher } from '@nestjs/cqrs';
import { PlaceOrderCommand } from './place-order.command';
import { Order } from './order.aggregate';
import { OrderRepository } from './order.repository';

@CommandHandler(PlaceOrderCommand)
export class PlaceOrderHandler implements ICommandHandler<PlaceOrderCommand> {
  constructor(
    private readonly repository: OrderRepository,
    private readonly publisher: EventPublisher,
  ) {}

  async execute(command: PlaceOrderCommand): Promise<void> {
    const order = this.publisher.mergeObjectContext(
      new Order(command.orderId),
    );

    order.place(command.total); // applies OrderPlacedEvent
    await this.repository.save(order);
    order.commit(); // now events reach the EventBus
  }
}

mergeClassContext for Factories

Sometimes you reconstruct aggregates inside a factory or repository rather than newing them directly in the handler. For that, mergeClassContext returns a publisher-aware subclass.

Every instance created from the merged class is automatically context-bound, so you do not have to call mergeObjectContext on each one.

Use mergeObjectContext for a single instance you already hold; use mergeClassContext when a factory will produce many instances.

import { EventPublisher } from '@nestjs/cqrs';
import { Order } from './order.aggregate';

export class OrderFactory {
  constructor(private readonly publisher: EventPublisher) {}

  create(orderId: string): Order {
    // Order becomes a publisher-aware subclass
    const ContextOrder = this.publisher.mergeClassContext(Order);
    return new ContextOrder(orderId);
  }
}

Defining a Domain Event

A domain event in NestJS is just a plain class — typically implementing the marker interface IEvent. Keep events immutable and carry only the data handlers need.

  • Use readonly fields populated in the constructor.
  • Name in past tense: OrderPlacedEvent, not PlaceOrder.
  • Include identifiers and the minimal payload, not entire entities.

Because events may be serialized (for event sourcing or message brokers), avoid putting behavior or service references on them.

import { IEvent } from '@nestjs/cqrs';

export class OrderPlacedEvent implements IEvent {
  constructor(
    public readonly orderId: string,
    public readonly customerId: string,
    public readonly total: number,
    public readonly occurredAt: Date = new Date(),
  ) {}
}

Handling the Event

An @EventsHandler(OrderPlacedEvent) class subscribes to the event on the bus. Its handle method runs the side effect: sending email, updating a read model, decrementing inventory.

Handlers should be idempotent where possible, because at-least-once delivery (in distributed setups) can replay an event. Keep them small and focused — one handler per concern.

Register handlers in the module's providers array so the bus discovers them.

import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { OrderPlacedEvent } from './order-placed.event';

@EventsHandler(OrderPlacedEvent)
export class OrderPlacedHandler implements IEventHandler<OrderPlacedEvent> {
  handle(event: OrderPlacedEvent): void {
    // side effect: e.g. enqueue a confirmation email
    console.log(`Order ${event.orderId} placed for ${event.total}`);
  }
}

Wiring the CqrsModule

To use any of this, import CqrsModule and register your handlers and aggregates' collaborators as providers. The module sets up the CommandBus, QueryBus, and EventBus, and exposes EventPublisher for injection.

  • Add command handlers, event handlers, and factories to providers.
  • Import CqrsModule in imports.

Without this import, injecting EventPublisher or EventBus fails at startup with an unresolved-dependency error.

import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { PlaceOrderHandler } from './place-order.handler';
import { OrderPlacedHandler } from './order-placed.handler';
import { OrderRepository } from './order.repository';

@Module({
  imports: [CqrsModule],
  providers: [PlaceOrderHandler, OrderPlacedHandler, OrderRepository],
})
export class OrdersModule {}

Commit After Persistence, Not Before

Order of operations matters. The recommended pattern is:

  • 1. Merge context onto the aggregate.
  • 2. Execute domain behavior (events are buffered via apply).
  • 3. Persist the aggregate inside a transaction.
  • 4. Call commit() only after the transaction succeeds.

If you commit before saving and the save fails, you have already published events for a state change that never persisted — leaving handlers acting on phantom data. For stronger guarantees, teams adopt the transactional outbox pattern, writing events to an outbox table in the same transaction and relaying them afterward.

Modeling the Buffer-Then-Publish Flow

The core idea — buffer events with apply, flush them with commit — can be reproduced in plain TypeScript to build intuition, with no NestJS at all. Here a tiny aggregate records events and a publisher drains them only when committed.

Run it and watch the handler fire only after commit() is called.

type DomainEvent = { name: string; payload: unknown };

class MiniAggregate {
  private events: DomainEvent[] = [];
  private publish: (e: DomainEvent) => void = () => {};

  setPublisher(fn: (e: DomainEvent) => void) {
    this.publish = fn; // mimics mergeObjectContext
  }

  apply(event: DomainEvent) {
    this.events.push(event); // buffer only
  }

  commit() {
    this.events.forEach((e) => this.publish(e));
    this.events = [];
  }
}

const order = new MiniAggregate();
order.apply({ name: 'OrderPlaced', payload: { id: 'A1', total: 50 } });
console.log('before commit: nothing published yet');

order.setPublisher((e) => console.log('handled:', e.name, e.payload));
order.commit();
console.log('after commit: buffer flushed');

Quick Check

You created an aggregate with new Order(id), called a method that uses this.apply(new OrderPlacedEvent(...)), then called order.commit() — but no event handler ever runs. What is the most likely cause?

Recap

You learned how NestJS CQRS turns aggregates into event emitters:

  • AggregateRoot gives apply() (buffer an event) and commit() (flush to the EventBus).
  • A direct new uses a no-op publisher — wire the real one with EventPublisher.mergeObjectContext for a single instance, or mergeClassContext for factory-produced instances.
  • Domain events are immutable past-tense classes implementing IEvent, carrying only the needed payload.
  • @EventsHandler classes react to events; keep them small and idempotent.
  • Import CqrsModule and register handlers in providers.
  • Commit after persistence so events never describe a state that failed to save; consider a transactional outbox for stronger delivery guarantees.

자주 묻는 질문

“도메인 이벤트와 AggregateRoot” 강의는 무료인가요?

네 — “도메인 이벤트와 AggregateRoot” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“도메인 이벤트와 AggregateRoot”에서 뭘 배우나요?

EventBus와 mergeObjectContext를 사용해 애그리게이트 루트에서 도메인 이벤트를 발생시키고 발행합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“도메인 이벤트와 AggregateRoot” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 명령, 처리기 및 CommandBus
  2. 쿼리와 읽기 모델 프로젝션
  3. 도메인 이벤트와 AggregateRoot
  4. 장시간 실행되는 워크플로를 위한 사가
← NestJS Enterprise Backend APIs(으)로 돌아가기