1 | 'use strict';
|
2 |
|
3 | const _ = require('lodash');
|
4 | const domain = require('domain');
|
5 | const cryptoRandomString = require('crypto-random-string');
|
6 |
|
7 | const httpInfraSymbol = Symbol('http-infra');
|
8 |
|
9 | function requireCorrelation() {
|
10 | if (!domain.active[httpInfraSymbol]) {
|
11 | throw new Error('Active domain isn\'t registered.');
|
12 | }
|
13 | }
|
14 |
|
15 | module.exports = {
|
16 | registerCorrelation(authenticatedEntity = null, requestId = null) {
|
17 | const activeDomain = domain.active;
|
18 |
|
19 | if (activeDomain[httpInfraSymbol]) {
|
20 | throw new Error('Can\'t register correlation. Domain is already registered');
|
21 | }
|
22 |
|
23 | if (!requestId) {
|
24 | requestId = cryptoRandomString({ length: 16, type: 'alphanumeric' });
|
25 | }
|
26 |
|
27 | activeDomain[httpInfraSymbol] = {
|
28 | authenticatedEntity,
|
29 | requestId
|
30 | };
|
31 | },
|
32 |
|
33 | extendCorrelationId(baseId) {
|
34 | const activeDomain = domain.active;
|
35 | _.set(
|
36 | activeDomain[httpInfraSymbol],
|
37 | 'requestId',
|
38 | `${baseId}:${cryptoRandomString({ length: 16, type: 'alphanumeric' })}`
|
39 | );
|
40 | },
|
41 |
|
42 | getRequestId() {
|
43 | requireCorrelation();
|
44 |
|
45 | return domain.active[httpInfraSymbol].requestId;
|
46 | },
|
47 |
|
48 | getAuthenticatedEntity() {
|
49 | requireCorrelation();
|
50 |
|
51 | return domain.active[httpInfraSymbol].authenticatedEntity;
|
52 | },
|
53 |
|
54 | isAuthenticatedEntity() {
|
55 | return !(_.isUndefined(domain.active)) &&
|
56 | !(_.isNull(domain.active[httpInfraSymbol].authenticatedEntity));
|
57 | },
|
58 |
|
59 | setAuthenticatedEntity(authenticatedEntity, allowOverride) {
|
60 | const httpInfraData = domain.active[httpInfraSymbol];
|
61 |
|
62 | if (!httpInfraData) {
|
63 | throw new Error('Can\'t set authenticated entity. Domain isn\'t registered.');
|
64 | }
|
65 |
|
66 | if (!allowOverride && httpInfraData.authenticatedEntity) {
|
67 | throw new Error('Can\'t set authenticated entity. Another entity is already set.');
|
68 | }
|
69 |
|
70 | httpInfraData.authenticatedEntity = authenticatedEntity;
|
71 | },
|
72 | };
|