-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
36 lines (34 loc) · 972 Bytes
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { Context } from './context.ts';
export interface Middleware {
(context: Context, next: () => Promise<void>): Promise<void> | void
}
/**
* 将多个中间件功能合成成一个中间件功能
* @param middleware
*/
export function compose(
middleware: Middleware[]
): (context: Context) => Promise<void> {
return function (context: Context, next?: () => Promise<void>) {
let index = -1;
/**
* 调度
* @param i
*/
async function dispatch(i: number) {
if (i <= index) {
throw new Error('next() called multiple times');
}
index = i;
let fn: Middleware | undefined = middleware[i];
if (i === middleware.length) {
fn = next;
}
if (!fn) {
return;
}
return fn(context, dispatch.bind(null, i + 1));
}
return dispatch(0);
}
}