-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
47 lines (42 loc) · 1.59 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
const uuid = require('uuid')
/**
* Mali request ID metadata middleware. If the call has metadata with the request ID
* (or specified property) sets it into the context into target property. If request ID
* is not present creates one using UUID and sets it into metadata and context.
* @module @malijs/requestid
*
* @param {Options} options
* @param {String} options.name Optional name of the metadata object property. Default: <code>'requestId'</code>
* @param {String|Boolean} options.target Optional name of the <code>ctx</code> property to set request id into.
* If not provided it is equal to <code>options.name</code>.
* @param {Function} options.generator Synchronous function to generate the request id if not present.
* Has to return a string. Default: <code>uuid</code> library.
*
* @example
* const rid = require('@malijs/requestid')
*
* app.use(rid())
* app.use('myFn', async (ctx, next) => {
* console.log(ctx.requestId) // request ID from metadata
* await next()
* })
*/
module.exports = function requestId (options = {}) {
const opts = Object.assign({
name: 'requestId',
generator: uuid
}, options)
if (typeof opts.target !== 'string' && typeof opts.target !== 'boolean') {
opts.target = opts.name
}
return function rid (ctx, next) {
const mn = opts.name.toLowerCase()
if (!ctx.metadata[mn]) {
ctx.metadata[mn] = (opts.generator)()
}
if (typeof opts.target === 'string' && opts.target) {
ctx[opts.target] = ctx.metadata[mn]
}
return next()
}
}