Saga Orchestrator With Compensation
Coordinate distributed transactions with a saga pattern and compensation functions for rollback on failure.
Code
interface SagaStep<T>{execute:()=>Promise<T>;compensate:(result:T)=>Promise<void>;}export class SagaOrchestrator{private steps:SagaStep<any>[]=[];private results:any[]=[];add<T>(step:SagaStep<T>):this{this.steps.push(step);return this;}async run():Promise<any[]>{for(let i=0;i<this.steps.length;i++){try{const result=await this.steps[i].execute();this.results.push(result);}catch(e){await this.compensate(i);throw e;}}return this.results;}private async compensate(failedIndex:number):Promise<void>{for(let i=failedIndex-1;i>=0;i--){try{await this.steps[i].compensate(this.results[i]);}catch(e){console.error('compensation failed for step',i,e);}}}}Report a problem with this exampleOpens a pre-filled issue on GitHub.