Last active
September 27, 2021 06:18
-
-
Save nuintun/ca572e8f2fac40cbb6f8743884b67ae4 to your computer and use it in GitHub Desktop.
compose TypeScript 增强版
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
/** | |
* @module compose | |
*/ | |
export type Next<C> = (context: C) => Promise<C>; | |
export type Middleware<C> = (context: C, next: Next<C>) => Promise<C> | C; | |
export type ComposedMiddleware<C> = (context: C, next?: Next<C>) => Promise<C>; | |
/** | |
* @function compose | |
* @description compose koa middlewares | |
* @param {function[]} middlewares | |
* @returns {function} | |
*/ | |
export default function compose<C>(middlewares: Middleware<C>[]): ComposedMiddleware<C> { | |
const done = async (context: C): Promise<C> => context; | |
const compose = middlewares.reduce((compose, middleware) => { | |
return (context, next) => { | |
return compose(context, async context => middleware(context, next)); | |
}; | |
}); | |
return async (context, next = done) => { | |
return compose ? compose(context, next) : next(context); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment