-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
41 lines (37 loc) · 1.16 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
/**
* Expose `responseTime()`.
*/
module.exports = responseTime;
const defaultProps = { hrtime: false };
/**
* @typedef {import("koa").Middleware} Middleware
*/
/**
* Add X-Response-Time header field.
* @param {Object} options options dictionary. { hrtime }
* @param {boolean} options.hrtime
* - `true` to use time in nanoseconds.
* - `false` to use time in milliseconds.
* Default is `false` to keep back compatible.
* @return {Middleware} Koa Middleware
* @api public
*/
function responseTime(options = defaultProps) {
const hrtime = options && options.hrtime;
const header = (options && options.header) || 'X-Response-Time';
return function responseTime(ctx, next) {
const 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(header, delta + 'ms');
});
};
}