UNPKG

@hiki9/rich-domain

Version:

Rich Domain is a library that provides a set of tools to help you build complex business logic in NodeJS using Domain Driven Design principles.

69 lines 2.52 kB
"use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.Aggregate = void 0; const entity_1 = require("./entity"); const ids_1 = require("./ids"); const DOMAIN_EVENTS = Symbol('AggregateEvents'); class Aggregate extends entity_1.Entity { constructor(input, config) { super(input, { ...config, isAggregate: true }); this.isAggregate = true; this[_a] = []; const instance = this.constructor; instance?.hooks?.onCreate?.(this); } hashCode() { const name = Reflect.getPrototypeOf(this); return new ids_1.Id(`[Aggregate@${name?.constructor?.name}]:${this.props.id}`); } addEvent(domainEvent, replace) { const shouldReplace = replace === 'REPLACE_DUPLICATED'; if (Boolean(shouldReplace)) { this.removeEvent(domainEvent.eventName); } this[DOMAIN_EVENTS].push(domainEvent); } clearEvents() { this[DOMAIN_EVENTS].splice(0, this[DOMAIN_EVENTS].length); } removeEvent(eventName) { this[DOMAIN_EVENTS] = this[DOMAIN_EVENTS].filter((domainEvent) => domainEvent.eventName !== eventName); } getEvents(eventName) { if (eventName) { return this[DOMAIN_EVENTS].filter((domainEvent) => domainEvent.eventName === eventName); } return this[DOMAIN_EVENTS]; } hasEvent(eventName) { return this[DOMAIN_EVENTS].some((domainEvent) => domainEvent.eventName === eventName); } async dispatch(eventName, eventPublisher) { const promisesQueue = []; for (const event of this[DOMAIN_EVENTS]) { if (event.aggregate.id.isEqual(this.id) && event.eventName === eventName) { promisesQueue.push(eventPublisher.publish(event)); this.removeEvent(eventName); } } await Promise.all(promisesQueue); } async dispatchAll(eventPublisher) { const promisesQueue = []; for (const event of this[DOMAIN_EVENTS]) { promisesQueue.push(eventPublisher.publish(event)); } for (const prop in this.props) { const currentValue = this.props[prop]; if (currentValue instanceof Aggregate) { promisesQueue.push(currentValue.dispatchAll(eventPublisher)); } } await Promise.all(promisesQueue); this.clearEvents(); } } exports.Aggregate = Aggregate; _a = DOMAIN_EVENTS; //# sourceMappingURL=aggregate.js.map