-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (42 loc) · 1.38 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
'use strict';
function strengthan(handler, timeout) {
timeout = timeout || handler.timeout;
var timeoutfunc = (_, reject) => {
setTimeout(() => { reject(new Error('timeout')); }, timeout);
};
return (req, res) => {
var timeoutPromise = timeout ? new Promise(timeoutfunc) : null;
var successPromise = new Promise((resolve, reject) => {
res.on('finish', () => {resolve()});
var handlerResult = handler(req, res);
var isPromise = handlerResult != undefined && handlerResult['then'];
if (isPromise) {
handlerResult.then((promiseHandlerResult) => {
processhandlerResult(promiseHandlerResult, res, reject);
}).catch((e) => {
reject(e);
});
} else {
processhandlerResult(handlerResult, res, reject);
}
});
return Promise.race([successPromise, timeoutPromise]);
};
}
function processhandlerResult(handlerResult, res, reject) {
try {
if (handlerResult === undefined) {
return;
} else if (handlerResult === null || handlerResult === '') {
try {
res.statusCode = 204;
} catch { }
res.end();
} else if (handlerResult.constructor === String) {
res.end(handlerResult);
} else {
reject(new Error(`Expect to return string/null/undefined, but return unexpected: ${typeof(handlerResult)}`));
}
} catch { }
}
module.exports = strengthan;