1 | const uuid = require('uuid/v1');
|
2 | const HttpClient = require('./client');
|
3 |
|
4 | const NAMESPACE = 'ROBBYSON_HTTP_CLIENT_NAMESPACE';
|
5 | const CONTEXT = 'ROBBYSON_HTTP_CLIENT_CONTEXT';
|
6 |
|
7 | const continuation = require('./continuation-local-storage');
|
8 | const session = continuation.createNamespace(NAMESPACE);
|
9 |
|
10 | class RobbysonHttp {
|
11 | static setup (req, res, next) {
|
12 | let context;
|
13 |
|
14 | session.run(() => {
|
15 | session.set(CONTEXT, new RobbysonHttp(req));
|
16 | context = session.active;
|
17 | next();
|
18 | });
|
19 |
|
20 | res.on('finish', () => session.exit(context));
|
21 | res.on('close', () => 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 |
|
48 | module.exports = RobbysonHttp;
|