How to signal that the transaction completed

When we're sure that the transaction has completed, the DomainEvents subject provides a method to notify all Observers of each Domain Event of its occurrence.

// shared/domain/events/DomainEvents.ts

export class DomainEvents {
  private static handlersMap = {};
  private static markedAggregates: AggregateRoot<any>[] = [];

  ...

  /**
   * @method dispatchEventsForAggregate
   * @static
   * @desc When all we know is the ID of the aggregate, call this
   * in order to dispatch any handlers subscribed to events on the
   * aggregate.
   */

  public static dispatchEventsForAggregate(id: UniqueEntityID): void {
    const aggregate = this.findMarkedAggregateByID(id);

    if (aggregate) {
      this.dispatchAggregateEvents(aggregate);
      aggregate.clearEvents();
      this.removeAggregateFromMarkedDispatchList(aggregate);
    }
  }

  private static removeAggregateFromMarkedDispatchList(
    aggregate: AggregateRoot<any>
  ): void {
    const index = this.markedAggregates.findIndex(a => a.equals(aggregate));
    this.markedAggregates.splice(index, 1);
  }

  /**
   * @method dispatchAggregateEvents
   * @static
   * @private
   * @desc Call all of the handlers for any domain events on this aggregate.
   */

  private static dispatchAggregateEvents(aggregate: AggregateRoot<any>): void {
    aggregate.domainEvents.forEach((event: IDomainEvent) =>
      this.dispatch(event)
    );
  }

  /**
   * @method dispatch
   * @static
   * @desc Invokes all of the subscribers to a particular domain event.
   */

  private static dispatch(event: IDomainEvent): void {
    const eventClassName: string = event.constructor.name;

    if (this.handlersMap.hasOwnProperty(eventClassName)) {
      const handlers: any[] = this.handlersMap[eventClassName];
      for (let handler of handlers) {
        handler(event);
      }
    }
  }
}

Continue reading

Howdy 👋

This is an online wiki and book about the basics of software design and architecture with TypeScript by Khalil Stemmler, Developer Advocate @ Apollo GraphQL .

This book’s mission is to teach developers the essential skills and practices to write testable, flexible, and maintainable code.

You can read more about the learning journey in the "Software Design and Architecture Roadmap 🖼️".

Already bought it?

If you’ve already purchased the book, click here to re-send your link. You can read the online wiki or download a copy of the book in PDF, EPUB, and Kindle versions.

Want access?

You can read the intro to the book for free and visit solidbook.io to buy the book/wiki (it's currently on pre-sale for 33% off)! For recent updates, click here. To get an idea of my writing, read some of my best free content here and here.

Need help?

Something not working? Have a question? You can reach me on Twitter or khalil@khalilstemmler.com.