-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (74 loc) · 2.11 KB
/
index.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const clone = require('clone');
function cloneObject (obj) {
if (!obj) return;
return Object
.keys(obj)
.reduce((copy, k) => {
copy[k] = obj[k];
return copy;
}, {});
}
function cloneContext (ctx) {
return {
response: cloneObject(ctx.response), // `clone` is not working for koa
state: clone(ctx.state) || ctx.state,
};
}
function assignContext (ctx, copy) {
if (ctx.response) Object.assign(ctx.response, copy.response);
ctx.state = copy.state;
}
/**
* Returns new middleware which select
* first one of passed.
* @param {Array} middleware
* @return {Function}
* @api public
*/
function some (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!');
}
/**
* @param {Object} ctx
* @return {Promise}
* @api public
*/
return function (ctx, next) {
// HACK: explicitly set to false to include in state
if (ctx.response && ctx.response._explicitStatus == null) ctx.response._explicitStatus = false;
// to handle only first successfull case
let resolved = false;
let initState = cloneContext(ctx);
const wrapResolve = (...args) => {
resolved = true;
// save first success next
if (next) next = next.bind(null, ...args);
};
return new Promise(async (resolve, reject) => {
let error;
let errorState;
let hasError = false;
for (let i=0; i < middleware.length; ++i) {
try {
await middleware[i](ctx, wrapResolve);
if (resolved) break;
} catch (e) {
if (!hasError) {
error = e;
hasError = true;
}
}
if (!errorState) errorState = cloneContext(ctx);
// restore state after error
assignContext(ctx, initState);
}
if (resolved) return resolve(next && next());
if (errorState) assignContext(ctx, errorState);
if (hasError) return reject(error);
resolve();
});
};
}
module.exports = some;