Skip to content

Instantly share code, notes, and snippets.

@szanata
Created August 9, 2018 19:04
Show Gist options
  • Save szanata/bf80bc8e9c6cb9b688b6c468c8d65da8 to your computer and use it in GitHub Desktop.
Save szanata/bf80bc8e9c6cb9b688b6c468c8d65da8 to your computer and use it in GitHub Desktop.
Atomik Pipeline JS
const setSym = Symbol( 'operations' );
module.exports = class AtomikPipeline {
constructor( operationsSet ) {
this[setSym] = operationsSet;
}
async run( _param ) {
const rollback = [];
let param = _param;
for ( const item of this[setSym] ) {
if ( item.rollback ) {
rollback.push( item.rollback );
}
try {
param = await item.operation( param );
} catch ( err ) {
await rollback.reverse()
.reduce( ( chain, op ) => chain.then( op ), Promise.resolve( param ) );
throw err;
}
}
return param;
}
};
// Usage
const operations = new Set()
.add( { operation: function1, rollback: null } )
.add( { operation: function2, rollback: rollbackFn1 } )
.add( { operation: function3, rollback: rollbackFn2 } )
.add( { operation: function4, rollback: rollbackFn3 } );
const result = await new AtomikPipeline( operations ).run( args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment