You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
1.1 KiB
JavaScript
33 lines
1.1 KiB
JavaScript
const clsHooked = require('cls-hooked');
|
|
var NAMESPACE = '';
|
|
const {v4: uuid} = require('uuid');
|
|
|
|
module.exports = {
|
|
init(ns) {
|
|
return clsHooked.createNamespace(NAMESPACE = ns);
|
|
},
|
|
getRequestId() {
|
|
if(!NAMESPACE) throw new Error('Namespace has not been inited');
|
|
return clsHooked.getNamespace(NAMESPACE)?.get('requestId');
|
|
},
|
|
getMetadata() {
|
|
if(!NAMESPACE) throw new Error('Namespace has not been inited');
|
|
|
|
return clsHooked.getNamespace(NAMESPACE)?.get('metadata');
|
|
},
|
|
assignRequestId(namespace, func, extraMetadata, incomingRequestId = uuid()) {
|
|
namespace.bind(async () => {
|
|
namespace.set('requestId', incomingRequestId);
|
|
if(extraMetadata) {
|
|
namespace.set('metadata', extraMetadata)
|
|
}
|
|
await func();
|
|
})();
|
|
},
|
|
attachContext(contextNamespace) {
|
|
return (req, res, next) => {
|
|
const ns = this.init(contextNamespace);
|
|
this.assignRequestId(ns, next, null, req.headers['x-requestid']);
|
|
}
|
|
},
|
|
} |