Skip to content

Instantly share code, notes, and snippets.

@shannonmoeller
Last active March 3, 2020 18:14
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 shannonmoeller/33d6173285a13862111690639ee7f819 to your computer and use it in GitHub Desktop.
Save shannonmoeller/33d6173285a13862111690639ee7f819 to your computer and use it in GitHub Desktop.
function createCascade() {
const middleware = [];
async function run(ctx, next = () => {}) {
// Reverse list to .pop() instead of .shift() for performance
const handlers = [...middleware, next].reverse();
async function runNext() {
if (handlers.length) {
const handler = handlers.pop();
await handler(ctx, runNext);
}
}
await runNext();
return ctx;
}
run.use = (handler) => {
middleware.push(handler);
return run;
};
return run;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment