UNPKG

@caidrive/shared

Version:

caidrive.shared.components

154 lines (153 loc) 3.24 kB
"use strict"; /** * What it does. * * @param name - Parameter description. * @returns Type and description of the returned object. * * @example * ``` * Write me later. * ``` */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Dispatcher = void 0; /** * */ class Dispatcher { /** * */ static dispatch(event) { /** * */ const eventName = event.constructor.name; if (this.handlers.hasOwnProperty(eventName)) { /** * */ const handlers = this.handlers[eventName]; /** * */ for (const handler of handlers) { handler(event); } } } /** * */ static getAggregate(id) { /** * */ let result = null; for (const aggregate of this.aggregates) { /** * */ if (aggregate.id.value.equals(id)) { result = aggregate; break; } } return result; } /** * */ static clearHandlers() { /** */ this.handlers = {}; } /** * */ static addAggregate(aggregate) { /** * */ if (!this.getAggregate(aggregate.id.value)) { /** */ this.aggregates.push(aggregate); } } /** * */ static removeAggregate(aggregate) { /** * */ for (let i = this.aggregates.length - 1; i >= 0; i--) { /** */ if (this.aggregates[i].equals(aggregate)) { /** */ this.aggregates.splice(i, 1); break; } } } /** * */ static register(cb) { /** * */ if (!this.handlers.hasOwnProperty(cb.eventName)) { this.handlers[cb.eventName] = []; } this.handlers[cb.eventName].push(cb.callback); } /** * */ static dispatchAggregateEvents(id) { try { /** */ const aggregate = this.getAggregate(id); /** */ if (aggregate) { /** * */ const { events } = aggregate; for (let i = events.length - 1; i >= 0; i--) { /** * */ try { /**/ const event = events[i]; this.dispatch(event); events.splice(i, 1); } catch (error) { continue; } } if (events.length === 0) { aggregate.clearEvents(); this.removeAggregate(aggregate); } } } catch (error) { } } } exports.Dispatcher = Dispatcher; /** * */ Dispatcher.handlers = {}; Dispatcher.aggregates = [];