UNPKG

@nestjs-cqrs-eventsourcing/core

Version:

Event sourcing for nestjs CQRS

65 lines (64 loc) 2.24 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventDispatcher = void 0; const debug_1 = __importDefault(require("debug")); const debug = (0, debug_1.default)('eventstore:eventdispatcher'); class EventDispatcher { constructor(publisher, store) { this.publisher = publisher; this.store = store; this.undispatchedEventsQueue = []; this.isRunning = false; } async start() { if (typeof this.publisher !== 'function') { const pubErrMsg = 'publisher not injected!'; debug(pubErrMsg); throw new Error(pubErrMsg); } if (!this.store || typeof this.store.getUndispatchedEvents !== 'function' || typeof this.store.setEventToDispatched !== 'function') { const storeErrMsg = 'store not injected!'; debug(storeErrMsg); throw new Error(storeErrMsg); } const events = await this.store.getUndispatchedEvents(); let triggered = false; if (events) { for (let i = 0, len = events.length; i < len; i += 1) { this.undispatchedEventsQueue.push(events[i]); triggered = false; if (i % 1000 === 0) { triggered = true; await this.trigger(); } } } if (!triggered) { await this.trigger(); } } async addUndispatchedEvents(events) { for (const e of events) { this.undispatchedEventsQueue.push(e); } await this.trigger(); } async trigger() { const queue = this.undispatchedEventsQueue || []; if (this.isRunning) return; this.isRunning = true; for (const e of queue) { debug('publish event...'); await this.publisher(e.payload); debug('set event to dispatched...'); await this.store.setEventToDispatched(e); } this.isRunning = false; } } exports.EventDispatcher = EventDispatcher;