-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
44 lines (35 loc) · 1.06 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
var timer = require('contimer'),
TIMER_LABEL = '__response_timer_label__';
/**
* @param {String} [label] Contimer timer label
* @param {Function} cb function(time: Number, req: http.IncomingMessage)
* @returns {Function} Middleware function(req: http.IncomingMessage, res: http.ServerResponse)
*/
module.exports = function requestTimeMiddleware(label, cb) {
if (typeof label === 'function') {
cb = label;
label = TIMER_LABEL;
}
return function(req, res, next) {
var timerStop = timer.start({}, label);
res
.on('finish', onFinish)
.on('close', onClose);
function onFinish() {
unbind();
var timeObj = timerStop();
cb(timeObj.time, req);
}
function onClose() {
unbind();
// FIXME: what should we do here?
cb(0, req);
}
function unbind() {
res
.removeListener('close', onClose)
.removeListener('finish', onFinish);
}
next();
};
};