Skip to content

Instantly share code, notes, and snippets.

@skrajewski
Created March 18, 2021 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skrajewski/7d2ad85e93921aecd6afd241677b7115 to your computer and use it in GitHub Desktop.
Save skrajewski/7d2ad85e93921aecd6afd241677b7115 to your computer and use it in GitHub Desktop.
Simple middleware processor
const pipe = async (stack, context) => {
const execute = (context) => {
let prevIndex = -1;
const runner = async (innerContext, index) => {
if (index == prevIndex) {
throw new Error('next() called more than once');
}
prevIndex = index;
const middleware = stack[index];
if (middleware) {
return await middleware(innerContext, (ctx) => runner(ctx, index + 1));
}
}
return runner(context, 0);
};
return execute(context);
};
const createPipe = (stack) => (context) => pipe(stack, context);
module.exports = { pipe, createPipe };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment