UNPKG

smart-saga-pattern

Version:

A library implementing the Saga pattern for microservice architecture

91 lines (90 loc) 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Transaction = void 0; const types_1 = require("../types"); /** * Represents a transaction step in a Saga */ class Transaction { /** * Creates a new Transaction * @param id Transaction ID * @param name Transaction name * @param action Function to execute for this transaction */ constructor(id, name, action) { this.result = null; this.error = null; this.id = id; this.name = name; this.status = types_1.TransactionStatus.PENDING; this.action = action; } /** * Gets the ID of the transaction */ getId() { return this.id; } /** * Gets the name of the transaction */ getName() { return this.name; } /** * Gets the status of the transaction */ getStatus() { return this.status; } /** * Gets the result of the transaction */ getResult() { return this.result; } /** * Gets the error of the transaction if it failed */ getError() { return this.error; } /** * Executes the transaction * @param context Context to pass to the transaction function * @param requiresCompensation Whether this transaction requires compensation in case of failure */ async execute(context, requiresCompensation = true) { try { this.status = types_1.TransactionStatus.EXECUTING; // Create metadata for the transaction const metadata = { id: this.id, name: this.name, startTime: Date.now(), requiresCompensation, }; // Execute the transaction with metadata this.result = await this.action(context, metadata); // Update metadata with end time metadata.endTime = Date.now(); this.status = types_1.TransactionStatus.COMPLETED; return this.result; } catch (error) { this.status = types_1.TransactionStatus.FAILED; this.error = error instanceof Error ? error : new Error(String(error)); throw this.error; } } /** * Resets the transaction to its initial state */ reset() { this.status = types_1.TransactionStatus.PENDING; this.result = null; this.error = null; } } exports.Transaction = Transaction;