-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
35 lines (31 loc) · 985 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
/**
* Expose `responseTime()`.
*/
module.exports = responseTime;
/**
* Add X-Response-Time header field.
* @param {Dictionary} options options dictionary. { hrtime }
*
* hrtime: boolean.
* `true` to use time in nanoseconds.
* `false` to use time in milliseconds.
* Default is `false` to keep back compatible.
* @return {Function}
* @api public
*/
function responseTime(options) {
let hrtime = options && options.hrtime;
return function responseTime(ctx, next) {
let start = ctx[Symbol.for('request-received.startAt')] ? ctx[Symbol.for('request-received.startAt')] : process.hrtime();
return next().then(() => {
let delta = process.hrtime(start);
// Format to high resolution time with nano time
delta = delta[0] * 1000 + delta[1] / 1000000;
if (!hrtime) {
// truncate to milliseconds.
delta = Math.round(delta);
}
ctx.set('X-Response-Time', delta + 'ms');
});
};
}