UNPKG

@nestjs-cqrs-eventsourcing/core

Version:

Event sourcing for nestjs CQRS

51 lines (50 loc) 1.5 kB
"use strict"; var _a, _b; Object.defineProperty(exports, "__esModule", { value: true }); exports.AggregateRoot = void 0; const INTERNAL_EVENTS = Symbol('internal_events'); const IS_AUTO_COMMIT_ENABLED = Symbol('is_auto_commit_enabled'); class AggregateRoot { constructor() { this[_a] = false; this[_b] = []; } get autoCommit() { return this[IS_AUTO_COMMIT_ENABLED]; } set autoCommit(value) { this[IS_AUTO_COMMIT_ENABLED] = value; } async publish(_event) { } async publishAll(_events) { } async commit() { await this.publishAll(this[INTERNAL_EVENTS]); this[INTERNAL_EVENTS].length = 0; } uncommit() { this[INTERNAL_EVENTS].length = 0; } getUncommittedEvents() { return this[INTERNAL_EVENTS]; } apply(event, isFromHistory = false) { if (!isFromHistory && !this.autoCommit) { this[INTERNAL_EVENTS].push(event); } const handler = this.getEventHandler(event); handler?.call(this, event); } loadFromHistory(history) { history.forEach((event) => this.apply(event, true)); } getEventHandler(event) { const handler = `on${this.getEventName(event)}`; return this[handler]; } getEventName(event) { const { constructor } = Object.getPrototypeOf(event); return constructor.name; } } exports.AggregateRoot = AggregateRoot; _a = IS_AUTO_COMMIT_ENABLED, _b = INTERNAL_EVENTS;