-
Notifications
You must be signed in to change notification settings - Fork 108
/
koa-compose.js
44 lines (36 loc) · 962 Bytes
/
koa-compose.js
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
37
38
39
40
41
42
43
44
// 洋葱🧅模型
function compose(middleware) {
if (!Array.isArray(middleware)) {
throw new TypeError('Middleware stack must be an array!')
}
for (const fn of middleware) {
if (typeof fn !=== 'function') {
throw new TypeError('Middleware must be composed of functions!')
}
}
return function (context, next) {
let index = -1;
return dispatch(0);
function dispatch(i) {
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'));
}
index = i;
let fn = middleware[i];
if (i === middleware.length) {
// 处理边界问题
fn = next;
}
if (!fn) {
return Promise.resolve();
}
try {
return Promise.resolve(fn(context, function next() {
return dispatch(i + 1);
}));
} catch(error) {
return Promise.reject(error);
}
}
}
}