Created
August 9, 2018 19:04
-
-
Save szanata/bf80bc8e9c6cb9b688b6c468c8d65da8 to your computer and use it in GitHub Desktop.
Atomik Pipeline JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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