UNPKG

smart-saga-pattern

Version:

A library implementing the Saga pattern for microservice architecture

74 lines (73 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SagaDefinition = exports.SagaDefinitionBuilder = void 0; const uuid_1 = require("uuid"); const Transaction_1 = require("../core/Transaction"); const Compensation_1 = require("../core/Compensation"); /** * Builder for creating Saga definitions * @template T Type of the input data * @template R Type of the result data (combined from all steps) */ class SagaDefinitionBuilder { constructor() { this.steps = []; } /** * Adds a step to the Saga definition * @param name Step name * @param transaction Transaction function * @param compensation Optional compensation function * @param requiresCompensation Whether this step requires compensation in case of failure */ step(name, transaction, compensation, requiresCompensation = true) { const stepId = (0, uuid_1.v4)(); const transactionObj = new Transaction_1.Transaction(stepId, name, transaction); const step = { transaction: transactionObj, requiresCompensation, }; if (compensation) { step.compensation = new Compensation_1.Compensation(stepId, `${name} Compensation`, stepId, // transactionId is the same as stepId compensation); } this.steps.push(step); // Type cast needed due to generic constraints return this; } /** * Builds the Saga definition */ build() { return new SagaDefinition(this.steps); } } exports.SagaDefinitionBuilder = SagaDefinitionBuilder; /** * Represents a Saga definition * @template T Type of the input data * @template R Type of the result data (combined from all steps) */ class SagaDefinition { /** * Creates a new Saga definition * @param steps Steps in the Saga */ constructor(steps) { this.steps = steps; } /** * Gets all steps in the Saga definition */ getSteps() { return [...this.steps]; } /** * Creates a new builder for a Saga definition * @template T Type of the input data * @template R Type of the result data */ static builder() { return new SagaDefinitionBuilder(); } } exports.SagaDefinition = SagaDefinition;