UNPKG

1.5 kBJavaScriptView Raw
1// const continuation = require('continuation-local-storage');
2const continuation = require('./continuation-local-storage')
3const requestify = require('requestify');
4const uuid = require('uuid/v1');
5const HttpClient = require('./client');
6
7const NAMESPACE = 'ROBBYSON_HTTP_CLIENT_NAMESPACE';
8const CONTEXT = 'ROBBYSON_HTTP_CLIENT_CONTEXT';
9
10class RobbysonHttp {
11 static setup (req, res, next) {
12 let context;
13 const session = continuation.createNamespace(NAMESPACE);
14 session.run(() => {
15 session.set(CONTEXT, new RobbysonHttp(req));
16 context = session.active;
17 next();
18 });
19
20 res.on('finish', () => {
21 session.exit(context);
22 });
23 }
24
25 constructor (req) {
26 const sessionId = uuid();
27 this.path = req.originalUrl;
28 this.system_id = req.system_id;
29 this.contractor_id = req.contractor_id;
30 this.user = req.user || {};
31 this.requestUUID = sessionId;
32 req.requestUUID = sessionId;
33
34 const headers = {};
35 if (this.contractor_id) { headers['x-contractor-id'] = this.contractor_id; }
36 if (this.user && this.user.sessionKey) { headers['x-robbyson-user'] = this.user.sessionKey; }
37 if (this.system_id) { headers['x-system-id'] = this.system_id; }
38
39 this.requestify = new HttpClient(headers);
40 }
41
42 static instance () {
43 return continuation.getNamespace(NAMESPACE).get(CONTEXT);
44 }
45
46}
47
48module.exports = RobbysonHttp;