This repository was archived by the owner on Jun 7, 2021. It is now read-only.
forked from yosuke-furukawa/server-timing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (69 loc) · 2.09 KB
/
Copy pathindex.js
File metadata and controls
82 lines (69 loc) · 2.09 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict'
const onHeaders = require('on-headers')
const Timer = require('./timer')
module.exports = function serverTiming(options) {
const opts = Object.assign({
total: true,
enabled: true,
serverName: "default",
}, options);
return (_, res, next) => {
const headers = []
const timer = new Timer()
if (res.setMetric) {
throw new Error('res.setMetric already exists.')
}
const startAt = process.hrtime()
res.setMetric = setMetric(headers, opts)
res.startTime = startTime(timer)
res.endTime = endTime(timer, res)
onHeaders(res, () => {
if (opts.total) {
const diff = process.hrtime(startAt)
const timeSec = (diff[0] * 1E3) + (diff[1] * 1e-6)
headers.push(`${opts.serverName}-total; dur=${timeSec}; desc="${opts.serverName} - Total Response Time"`)
}
timer.clear()
if (opts.enabled) {
const existingHeaders = res.getHeader('Server-Timing')
res.setHeader('Server-Timing', [].concat(existingHeaders || []).concat(headers).join(', '))
}
})
if (typeof next === 'function') {
next()
}
}
}
function setMetric(headers, opts) {
return (name, value, description) => {
if (typeof name !== 'string') {
return console.warn('1st argument name is not string')
}
if (typeof value !== 'number') {
return console.warn('2nd argument value is not number')
}
const metric = typeof description !== 'string' || !description ?
`${opts.serverName}-${name}; dur=${value}` : `${name}; dur=${value}; desc="${opts.serverName} - ${description}"`
headers.push(metric)
}
}
function startTime(timer) {
return (name, description) => {
if (typeof name !== 'string') {
return console.warn('1st argument name is not string')
}
timer.time(name, description)
}
}
function endTime(timer, res) {
return (name) => {
if (typeof name !== 'string') {
return console.warn('1st argument name is not string')
}
const obj = timer.timeEnd(name)
if (!obj) {
return
}
res.setMetric(obj.name, obj.value, obj.description)
}
}