Created
March 18, 2021 10:33
-
-
Save skrajewski/7d2ad85e93921aecd6afd241677b7115 to your computer and use it in GitHub Desktop.
Simple middleware processor
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 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