smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
62 lines (61 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SagaRunner = void 0;
const SagaBuilder_1 = require("./SagaBuilder");
const StructuredSagaOrchestrator_1 = require("../orchestration/StructuredSagaOrchestrator");
const SagaOrchestrator_1 = require("../orchestration/SagaOrchestrator");
/**
* Runner for executing Sagas built from decorated classes
*/
class SagaRunner {
/**
* Runs a Saga with all registered steps
* @param initialData Initial data for the Saga
* @param options Options for running the Saga
* @template T Type of the context
*/
static async runAll(initialData, options = {}) {
// Build Saga definition from all steps
const definition = SagaBuilder_1.SagaBuilder.buildFromAllSteps();
// Create and execute orchestrator
return this.createAndExecuteOrchestrator(definition, initialData, options);
}
/**
* Runs a Saga with specific step classes
* @param stepClasses Step classes to include in the Saga
* @param initialData Initial data for the Saga
* @param options Options for running the Saga
* @template T Type of the context
*/
static async run(stepClasses, initialData, options = {}) {
// Build Saga definition from specific steps
const definition = SagaBuilder_1.SagaBuilder.buildFromSteps(stepClasses);
// Create and execute orchestrator
return this.createAndExecuteOrchestrator(definition, initialData, options);
}
/**
* Creates and executes an orchestrator
* @param definition Saga definition
* @param initialData Initial data for the Saga
* @param options Options for running the Saga
* @template T Type of the context
*/
static async createAndExecuteOrchestrator(definition, initialData, options) {
// Set default options
const runOptions = {
useStructuredContext: true,
...options,
};
// Create orchestrator
let orchestrator;
if (runOptions.useStructuredContext) {
orchestrator = new StructuredSagaOrchestrator_1.StructuredSagaOrchestrator(definition, runOptions.sagaOptions, runOptions.stateStore);
}
else {
orchestrator = new SagaOrchestrator_1.SagaOrchestrator(definition, runOptions.sagaOptions, runOptions.stateStore);
}
// Execute the Saga
return (await orchestrator.execute(initialData));
}
}
exports.SagaRunner = SagaRunner;