UNPKG

smart-saga-pattern

Version:

A library implementing the Saga pattern for microservice architecture

90 lines (89 loc) 3.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SagaOrchestrator = void 0; const Saga_1 = require("../core/Saga"); const SagaExecutor_1 = require("./SagaExecutor"); const types_1 = require("../types"); /** * Orchestrator for executing Sagas * @template T Type of the data in the context * @template R Type of the result data from transactions */ class SagaOrchestrator extends Saga_1.Saga { /** * Creates a new SagaOrchestrator * @param definition Saga definition to orchestrate * @param options Saga options * @param stateStore Optional state store for persistence */ constructor(definition, options = {}, stateStore) { super(options); this.definition = definition; this.stateStore = stateStore; } /** * Executes the Saga * @param initialData Initial data for the Saga */ async execute(initialData) { try { // Update context with initial data if (initialData) { this.updateContext(initialData); } // Save initial state if state store is provided if (this.stateStore) { await this.stateStore.save(this.getId(), this.getContext()); } // Create executor and execute the Saga const executor = new SagaExecutor_1.SagaExecutor(this.definition, this.getContext()); const result = await executor.execute(); // Update context with result this.context = result; // Update state store if provided if (this.stateStore) { await this.stateStore.update(this.getId(), this.context); } return this.getContext(); } catch (error) { this.setStatus(types_1.SagaStatus.FAILED, error instanceof Error ? error.message : String(error)); // Update state store if provided if (this.stateStore) { await this.stateStore.update(this.getId(), this.context); } return this.getContext(); } } /** * Compensates the Saga (rolls back) */ async compensate() { try { this.setStatus(types_1.SagaStatus.COMPENSATING); // Update state store if provided if (this.stateStore) { await this.stateStore.update(this.getId(), this.context); } // Create executor and execute compensation const executor = new SagaExecutor_1.SagaExecutor(this.definition, this.getContext()); const result = await executor.execute(); // Update context with result this.context = result; // Update state store if provided if (this.stateStore) { await this.stateStore.update(this.getId(), this.context); } return this.getContext(); } catch (error) { this.setStatus(types_1.SagaStatus.COMPENSATION_FAILED, error instanceof Error ? error.message : String(error)); // Update state store if provided if (this.stateStore) { await this.stateStore.update(this.getId(), this.context); } return this.getContext(); } } } exports.SagaOrchestrator = SagaOrchestrator;