Skip to content

Instantly share code, notes, and snippets.

@lcanady
Last active December 7, 2020 22:23
Show Gist options
  • Select an option

  • Save lcanady/b7cb4e45a9edf31bbf04934cec74d1d8 to your computer and use it in GitHub Desktop.

Select an option

Save lcanady/b7cb4e45a9edf31bbf04934cec74d1d8 to your computer and use it in GitHub Desktop.
const execute: Pipe<T>["execute"] = async (context) => {
let prevIndex = -1;
/**
* Programatically go through each middleware and apply it to context before
* either moving on to the next middleware, or returning the final context
* object.
* @param index The current count of middleware executions.
* @param context The context object to send through the
* middleware pipeline.
*/
const handler = async (index: number, context: T): Promise<void | T> => {
if (index === prevIndex) {
throw new Error("next() already called.");
}
if (index === stack.length) return context;
prevIndex = index;
const middleware = stack[index];
if (middleware) {
await middleware(context, () => handler(index + 1, context));
}
};
const response = await handler(0, context);
if (response) return response;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment