-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (44 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
42
43
44
45
46
47
48
49
50
51
'use strict'
const cls = require('cls-hooked')
const uuidv4 = require('uuid/v4')
// generate a unique value for namespace
const nsid = `rtracer:${uuidv4()}`
const ns = cls.createNamespace(nsid)
/**
* Generates a request tracer middleware.
* @param {Object} options possible options
* @param {boolean} options.useHeader respect request header flag
* (default: `true`)
* @param {string} options.headerName request header name, used if `useHeader` is set to `true`
* (default: `X-Request-Id`)
*/
const middleware = ({
useHeader = true,
headerName = 'X-Request-Id'
} = {}) => {
return (req, res, next) => {
ns.bindEmitter(req)
ns.bindEmitter(res)
let requestId
if (useHeader) {
requestId = req.headers[headerName.toLowerCase()]
}
requestId = requestId || uuidv4()
ns.run(() => {
ns.set('requestId', requestId)
next()
})
}
}
/**
* Returns request tracer id or `undefined` in case if the call is made from an outside CLS context.
*/
const id = () => {
if (ns && ns.active) {
return ns.get('requestId')
}
}
module.exports = {
middleware,
id
}