forked from koa-modules/x-request-id
/
index.js
64 lines (55 loc) · 1.37 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
52
53
54
55
56
57
58
59
60
61
62
63
64
/*!
* x-request-id
* Copyright(c) 2015 Fangdun Cai
* MIT Licensed
*/
'use strict';
/**
* Module dependences.
*/
var debug = require('debug')('koa:x-request-id')
var uuid = require('node-uuid').v4;
const HTTP_X_REQUEST_ID_HEADER = 'X-Request-Id';
const REGEXP = /\-/g;
/**
* X-Request-Id:
*
* Generates a unique Request ID for every incoming HTTP request.
* This unique ID is then passed to your application as an HTTP header called
* `X-Request-Id`.
*
* @param {string} [key=HTTP_X_REQUEST_ID_HEADER]
* @param {bool} [noHyphen=false]
* @param {bool} [inject=false]
* @api public
*/
module.exports = xRequestId;
function xRequestId(app, options) {
options = options || {};
var key = options.key || HTTP_X_REQUEST_ID_HEADER;
var noHyphen = !!options.noHyphen;
var inject = !!options.inject;
if (inject) {
Object.defineProperty(app.request, 'id', {
get: function() {
return this._id;
},
set: function(id) {
this._id = id;
}
});
Object.defineProperty(app.context, 'id', {
get: function() {
return this.request.id;
}
});
}
return function* xRequestId(next) {
var id = this.id || this.query[key] || this.get(key) || uuid();
if (noHyphen) id = id.replace(REGEXP, '');
if (inject) this.request.id = id;
this.set(key, id);
debug('%s: %s', key, id);
yield * next;
}
}