UNPKG

@nestjs-cqrs-eventsourcing/core

Version:

Event sourcing for nestjs CQRS

79 lines (78 loc) 2.9 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StoreEventBus = void 0; const debug_1 = __importDefault(require("debug")); const debug2 = (0, debug_1.default)('eventstore:event-bus'); class StoreEventBus { constructor(viewEventBus, eventStore, dls, options) { this.viewEventBus = viewEventBus; this.eventStore = eventStore; this.dls = dls; this.options = options; } async publish(_event, _context) { throw new Error('Not allowed in this implementation'); } async publishAll(events, request) { if (!events.length) { return; } const iterate = [...events]; const lockId = this.getAggregateId(events); const release = await this.dls.getLock(lockId); for (const event of iterate) { await this.storeEvent(event, request); } debug2('await commit', lockId); await this.eventStore.commit(lockId); debug2('done commit', lockId); this.eventStore.logUncommitted(); await release(); } getAggregateId(events) { const allAggregates = events.map(evt => `${evt.eventAggregate}-${evt.id}`); const uniqueAggregates = [...new Set(allAggregates)]; if (uniqueAggregates.length !== 1) { throw new Error(`Error establishing aggregated id, aggregates: ${uniqueAggregates.join(',')}`); } return uniqueAggregates[0]; } async storeEvent(event, request) { const storableEvent = event; if (storableEvent.id === undefined || storableEvent.eventAggregate === undefined || storableEvent.eventVersion === undefined) { throw new Error('Events must implement StorableEvent interface'); } const userId = this.getUserId(request); if (!event.userId && (typeof userId === 'number' || typeof userId === 'string')) { event.userId = userId; } await this.eventStore.storeEvent(storableEvent); await this.viewEventBus.publish(event); } getUserId(request) { if (this.options.getUserId) { return this.options.getUserId(request); } if (request && typeof request === 'object' && 'user' in request && request.user && typeof request.user === 'object' && 'id' in request.user) { if (this.options.parseUserId) { return this.options.parseUserId(request.user.id); } if (!Number.isNaN(request.user.id)) { return Number(request.user.id); } } return undefined; } } exports.StoreEventBus = StoreEventBus;