/
index.js
46 lines (40 loc) · 1.08 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
'use strict';
const cls = require('cls-hooked');
const { createNamespace } = cls;
const Hoek = require('hoek');
const ns = createNamespace('hapi-request-context');
const patchBluebird = require('cls-bluebird');
patchBluebird(ns);
module.exports = {
register: function (server, options, next) {
Hoek.assert(!options.mapHeaders || Array.isArray(options.mapHeaders), new Error('"options.mapHeaders" is required to be an Array if set'));
server.ext('onRequest', function (req, reply) {
ns.bindEmitter(req.raw.req);
ns.bindEmitter(req.raw.res);
ns.run(function () {
if (options.mapHeaders && options.mapHeaders.length) {
options.mapHeaders.map(function (header) {
if (req.headers[header]) {
ns.set(header, req.headers[header]);
}
});
}
if(options.onRequest) {
options.onRequest(req, reply);
} else {
reply.continue();
}
});
});
next();
},
namespaceName: function() {
return 'hapi-request-context';
},
context: function() {
return ns;
}
};
module.exports.register.attributes = {
name: 'hapi-request-context'
};