forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequestId.js
More file actions
41 lines (34 loc) · 1.02 KB
/
Copy pathrequestId.js
File metadata and controls
41 lines (34 loc) · 1.02 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
'use strict';
const crypto = require('node:crypto');
const { AsyncLocalStorage } = require('node:async_hooks');
const requestContext = new AsyncLocalStorage();
function nanoid(size = 21) {
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz-';
const bytes = crypto.randomBytes(size);
let id = '';
for (const byte of bytes) id += alphabet[byte & 63];
return id;
}
function requestIdMiddleware(req, res, next) {
req.id = req.get('x-request-id') || `req_${nanoid()}`;
res.setHeader('X-Request-ID', req.id);
const originalJson = res.json.bind(res);
res.json = (body) => {
if (
body &&
typeof body === 'object' &&
!Array.isArray(body) &&
!Object.prototype.hasOwnProperty.call(body, 'request_id') &&
!Object.prototype.hasOwnProperty.call(body, 'error')
) {
body.request_id = req.id;
}
return originalJson(body);
};
requestContext.run({ requestId: req.id }, next);
}
module.exports = {
requestIdMiddleware,
requestContext,
nanoid,
};