-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.js
47 lines (39 loc) · 1023 Bytes
/
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
const co = require('co');
const Layer = require('express/lib/router/layer');
const noop = () => {};
Object.defineProperty(Layer.prototype, "handle", {
enumerable: true,
get: function() { return this.__handle; },
set: function(fn) {
if (isGenerator(fn)) {
fn = wrapGenerator(fn);
}
if (isAsync(fn)) {
fn = wrapAsync(fn);
}
this.__handle = fn;
}
});
function isGenerator(fn) {
const type = Object.toString.call(fn.constructor);
return type.indexOf('GeneratorFunction') !== -1;
}
function isAsync(fn) {
const type = Object.toString.call(fn.constructor);
return type.indexOf('AsyncFunction') !== -1;
};
function wrapGenerator(original) {
const wrapped = co.wrap(original);
return function(req, res, next = noop) {
wrapped(req, res)
.then(() => !res.finished && next())
.catch(next);
};
};
function wrapAsync(fn) {
return (req, res, next = noop) => {
fn(req, res, next)
.then(() => !res.finished && next())
.catch(next);
}
};