smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
86 lines (85 loc) • 2.59 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Compensation = void 0;
const types_1 = require("../types");
/**
* Represents a compensation step in a Saga
*/
class Compensation {
/**
* Creates a new Compensation
* @param id Compensation ID
* @param name Compensation name
* @param transactionId ID of the transaction being compensated
* @param action Function to execute for this compensation
*/
constructor(id, name, transactionId, action) {
this.error = null;
this.id = id;
this.name = name;
this.transactionId = transactionId;
this.status = types_1.TransactionStatus.PENDING;
this.action = action;
}
/**
* Gets the ID of the compensation
*/
getId() {
return this.id;
}
/**
* Gets the name of the compensation
*/
getName() {
return this.name;
}
/**
* Gets the status of the compensation
*/
getStatus() {
return this.status;
}
/**
* Gets the error of the compensation if it failed
*/
getError() {
return this.error;
}
/**
* Executes the compensation
* @param context Context to pass to the compensation function
* @param transactionOutput Output from the transaction being compensated
* @param transactionName Name of the transaction being compensated
*/
async execute(context, transactionOutput, transactionName = "Unknown Transaction") {
try {
this.status = types_1.TransactionStatus.EXECUTING;
// Create metadata for the compensation
const metadata = {
id: this.id,
name: this.name,
startTime: Date.now(),
transactionId: this.transactionId,
transactionName,
};
// Execute the compensation with metadata
await this.action(context, transactionOutput, metadata);
// Update metadata with end time
metadata.endTime = Date.now();
this.status = types_1.TransactionStatus.COMPLETED;
}
catch (error) {
this.status = types_1.TransactionStatus.FAILED;
this.error = error instanceof Error ? error : new Error(String(error));
throw this.error;
}
}
/**
* Resets the compensation to its initial state
*/
reset() {
this.status = types_1.TransactionStatus.PENDING;
this.error = null;
}
}
exports.Compensation = Compensation;