Last active
December 7, 2020 22:23
-
-
Save lcanady/b7cb4e45a9edf31bbf04934cec74d1d8 to your computer and use it in GitHub Desktop.
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 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