-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompose.js
65 lines (59 loc) · 1.8 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var flatten = require("array-flatten");
function compose() {
var handlers = [];
for (var _i = 0; _i < arguments.length; _i++) {
handlers[_i] = arguments[_i];
}
var middleware = generate(handlers);
return function(req, res, done) { return middleware(null, req, res, done); };
}
exports.compose = compose;
function errors() {
var handlers = [];
for (var _i = 0; _i < arguments.length; _i++) {
handlers[_i] = arguments[_i];
}
return generate(handlers);
}
exports.errors = errors;
function generate(handlers) {
var stack = flatten(handlers);
for (var _i = 0, stack_1 = stack; _i < stack_1.length; _i++) {
var handler = stack_1[_i];
if (typeof handler !== 'function') {
throw new TypeError('Handlers must be a function');
}
}
return function middleware(err, req, res, done) {
var index = -1;
function dispatch(pos, err) {
var handler = stack[pos];
index = pos;
if (index === stack.length)
return done(err);
function next(err) {
if (pos < index) {
throw new TypeError('`next()` called multiple times');
}
return dispatch(pos + 1, err);
}
try {
if (handler.length === 4) {
if (err) {
return handler(err, req, res, next);
}
} else {
if (!err) {
return handler(req, res, next);
}
}
} catch (e) {
if (index > pos)
throw e;
return next(e);
}
return next(err);
}
return dispatch(0, err);
};
}