Class AggregateRoot<T>Abstract

Base class for Aggregate Roots in Domain-Driven Design.

An Aggregate Root is the entry point to an aggregate, which is a cluster of domain objects that can be treated as a single unit. The Aggregate Root ensures the consistency of changes within the aggregate boundary and manages domain events.

class Order extends AggregateRoot<'Order'> {
constructor(id: EntityId<'Order'>, private items: OrderItem[]) {
super(id, new Date(), new Date());
}

addItem(item: OrderItem): void {
this.items.push(item);
this.record({ occurredAt: new Date(), orderId: this.id.value, itemId: item.id });
this.touch();
}

checkout(): void {
// Business logic...
this.record({ occurredAt: new Date(), orderId: this.id.value });
}
}

// Later, publish events:
const events = order.pullDomainEvents();
await eventBus.publish(events);

Type Parameters

  • T extends string

    Phantom type representing the aggregate type (e.g., 'User', 'Order')

Hierarchy (View Summary)

Accessors

  • get createdAt(): Date

    Gets the timestamp when this entity was created.

    Returns Date

  • get updatedAt(): Date

    Gets the timestamp when this entity was last updated.

    Returns Date

Constructors

Methods

  • Protected

    Records a domain event that occurred within this aggregate. Events are stored internally and can be retrieved later for publishing.

    Parameters

    Returns void

    this.record({
    occurredAt: new Date(),
    userId: this.id.value,
    email: 'user@example.com'
    });
  • Retrieves and clears all domain events recorded by this aggregate. This is typically called after the aggregate is persisted, to publish the events.

    Returns DomainEvent[]

    An array of domain events

    await repository.save(order);
    const events = order.pullDomainEvents();
    await eventBus.publish(events);
  • Checks if this aggregate has any recorded domain events.

    Returns boolean

    true if there are pending domain events, false otherwise

  • Protected

    Updates the updatedAt timestamp to the current time. Should be called whenever the entity's state changes.

    Returns void

  • Compares this entity with another for equality based on identity. Two entities are equal if they have the same ID and are of the same type.

    Parameters

    • other: Entity<T>

      The other entity to compare with

    Returns boolean

    true if the entities are equal, false otherwise