Last active
January 14, 2025 07:24
-
-
Save mary-ext/5f46b4598ecd82d7f98d512e80fac7c3 to your computer and use it in GitHub Desktop.
Middleware-style hook runner
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
type Middleware<TParams extends any[], TReturn> = ( | |
...params: [...TParams, next: (...params: TParams) => TReturn] | |
) => TReturn; | |
const exhausted = () => { | |
throw new Error('middleware chain exhausted'); | |
}; | |
export const createMiddlewareRunner = <TParams extends any[], TReturn>( | |
middlewares: [...Middleware<TParams, TReturn>[], Middleware<TParams, TReturn>], | |
) => { | |
// prettier-ignore | |
return middlewares.reduceRight<(...params: TParams) => TReturn>( | |
(next, run) => (...args) => run(...args, next), | |
exhausted, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment