forked from kaievns/express-yields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (38 loc) · 1000 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
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);
}
else {
fn = wrapThenable(fn);
}
this.__handle = fn;
}
});
function isGenerator(fn) {
const type = Object.toString.call(fn.constructor);
return type.indexOf('GeneratorFunction') !== -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 wrapThenable(fn) {
return (req, res, next = noop) => {
const rv = fn(req, res, next);
if (rv && rv.then) {
Promise.resolve(rv)
.then(() => !res.finished && next())
.catch(next);
}
};
}