Last active
May 9, 2023 02:31
-
-
Save nuintun/e249c61a897e1c5c7132f02b9018e603 to your computer and use it in GitHub Desktop.
koa-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 interface Next { | |
(): Promise<void>; | |
} | |
export interface Composed<C> { | |
(context: C, next?: Next): Promise<void>; | |
} | |
export interface Middleware<C> { | |
(context: C, next: Next): Promise<void> | void; | |
} | |
/** | |
* @function compose | |
* @description compose koa middlewares | |
* @param {function[]} middlewares | |
* @returns {function} | |
*/ | |
export default function compose<C>(middlewares: Middleware<C>[]): Composed<C> { | |
const done = async (): Promise<void> => {}; | |
const compose = middlewares.reduce((compose, middleware) => { | |
return (context, next) => { | |
return compose(context, async () => { | |
middleware(context, next); | |
}); | |
}; | |
}); | |
return async (context, next = done) => { | |
return compose ? compose(context, next) : next(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment