@autofleet/node-common 1.1.52 → 1.1.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/network/index.js CHANGED
@@ -11,6 +11,7 @@ require('dotenv').config();
11
11
  if (process.env.NODE_ENV === 'test') {
12
12
  axios.defaults.adapter = httpAdapter;
13
13
  }
14
+
14
15
  const HTTPMethods = [
15
16
  'get',
16
17
  'post',
@@ -20,42 +21,32 @@ const HTTPMethods = [
20
21
  'patch',
21
22
  'options',
22
23
  ];
24
+
23
25
  const defaultSettings = {
24
26
  timeout: 2500,
25
27
  headers: { 'X-AF-AUTH': 'ANYONE' },
26
28
  paramsSerializer: params => qs.stringify(params, { arrayFormat: 'brackets' }),
27
29
  };
28
- const getHttpResponseObject = (response) => {
29
- const maxBodySize = 1000;
30
- const jsonBody = response.config.data ? JSON.stringify(response.config.data) : '';
31
- const body = jsonBody.length > maxBodySize ? jsonBody.substring(0, maxBodySize) : response.config.data;
32
- return {
33
- status: response.status,
34
- requestUrl: response.config.url,
35
- query: response.config.params,
36
- body,
37
- requestMethod: response.config.method.toUpperCase(),
38
- };
39
- };
40
- const getHttpRequestObject = (request) => {
41
- const maxBodySize = 1000;
42
- const jsonBody = request.data ? JSON.stringify(request.data) : '';
43
- const body = jsonBody.length > maxBodySize ? jsonBody.substring(0, maxBodySize) : request.data;
44
- return {
45
- headers: request.headers,
46
- query: request.params,
47
- body,
48
- };
49
- }
30
+
31
+ const getHttpRequestObject = response => ({
32
+ status: response.status,
33
+ requestUrl: response.config.url,
34
+ query: response.config.params,
35
+ body: response.config.data,
36
+ requestMethod: response.config.method.toUpperCase(),
37
+ });
38
+
50
39
  module.exports = class Network {
51
40
  constructor(settings = {}) {
52
41
  this.settings = Object.assign({}, defaultSettings, settings);
53
42
  this.createBaseUrl();
43
+
54
44
  this.axios = axios.create(this.settings);
55
45
  this.addRetry(settings);
56
46
  this.buildClassHttpMethods();
57
47
  this.addLogs();
58
48
  }
49
+
59
50
  addRetry(settings) {
60
51
  axiosRetry(this.axios, {
61
52
  retries: 0,
@@ -63,25 +54,33 @@ module.exports = class Network {
63
54
  ...settings,
64
55
  });
65
56
  }
57
+
66
58
  addLogs() {
67
59
  const logger = Logger();
68
60
  this.axios.interceptors.request.use((request) => {
69
- logger.info(`Start Request: [${request.method.toUpperCase()}] ${request.baseURL} ${request.url}`, getHttpRequestObject(request));
61
+ logger.info(`Start Request: [${request.method.toUpperCase()}] ${request.baseURL} ${request.url}`, {
62
+ headers: request.headers,
63
+ query: request.params,
64
+ body: request.data,
65
+ });
70
66
  return request;
71
67
  });
68
+
72
69
  this.axios.interceptors.response.use((response) => {
73
- logger.info(`Finish Request: [${response.config.method.toUpperCase()} ${response.config.url}`, getHttpResponseObject(response));
70
+ logger.info(`Finish Request: [${response.config.method.toUpperCase()} ${response.config.url}`, getHttpRequestObject(response));
74
71
  return response;
75
72
  }, (error) => {
76
- logger.error('Finish Request with error', { data: error.response ? error.response.data : undefined, ...getHttpResponseObject(error.response || error) });
73
+ logger.error('Finish Request with error', { data: error.response ? error.response.data : undefined, ...getHttpRequestObject(error.response || error) });
77
74
  // throw error;
78
75
  return error;
79
76
  });
80
77
  }
78
+
81
79
  createBaseUrl() {
82
80
  if (!this.settings.serviceUrl && !this.settings.serviceName) {
83
81
  throw new Error('At least one of the settings Missing serviceUrl or serviceName');
84
82
  }
83
+
85
84
  const { settings } = this;
86
85
  if (settings.serviceUrl) {
87
86
  settings.baseURL = settings.serviceUrl;
@@ -93,6 +92,7 @@ module.exports = class Network {
93
92
  }
94
93
  }
95
94
  }
95
+
96
96
  /**
97
97
  * Build class methods that wrap axios methods
98
98
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/node-common",
3
- "version": "1.1.52",
3
+ "version": "1.1.54",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "coverage": "jest --coverage --forceExit --runInBand",
@@ -22,10 +22,8 @@
22
22
  },
23
23
  "homepage": "https://gitlab.com/AutoFleet/node-common#README",
24
24
  "dependencies": {
25
- "@google-cloud/logging-winston": "^0.10.1",
26
- "@google-cloud/monitoring": "^0.6.0",
27
- "@google-cloud/profiler": "^0.2.0",
28
- "@google-cloud/pubsub": "^0.19.0",
25
+ "@google-cloud/logging-winston": "^0.10.2",
26
+ "@google-cloud/pubsub": "^0.20.1",
29
27
  "axios": "^0.18.0",
30
28
  "axios-retry": "^3.1.0",
31
29
  "dotenv": "^5.0.1",
package/settings/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ const EventEmitter = require('events');
1
2
  const NodeCache = require('node-cache');
2
3
  const Network = require('../network');
3
4
  const Logger = require('../logger');
@@ -6,17 +7,22 @@ const logger = Logger();
6
7
  require('dotenv').config();
7
8
 
8
9
  const fiveMinutes = 60 * 5;
10
+ const watingToNetwork = 'watingToNetwork';
9
11
 
10
12
  const findUrl = serviceUrl => serviceUrl ||
11
13
  (process.env.SETTING_MS_SERVICE_HOST && process.env.SETTING_MS_SERVICE_HOST.length > 0 ? `http://${process.env.SETTING_MS_SERVICE_HOST}/` : undefined) ||
12
14
  (process.env.NODE_ENV !== 'test' ? 'http://setting-ms.autofleet.io/' : 'http://localhost:9999/');
13
15
 
14
16
  module.exports = class SettingsManager {
17
+ static readNetworkValue(networkValue, defaultValue) {
18
+ return typeof networkValue !== 'undefined' ? networkValue : defaultValue;
19
+ }
15
20
  constructor({ serviceUrl, ttl = fiveMinutes } = {}) {
16
21
  const localServiceUrl = findUrl(serviceUrl);
17
22
 
18
23
  this.ttl = ttl;
19
24
  this.settingsCache = new NodeCache();
25
+ this.networkEvents = new EventEmitter();
20
26
  this.network = new Network({
21
27
  serviceUrl: localServiceUrl,
22
28
  });
@@ -30,6 +36,13 @@ module.exports = class SettingsManager {
30
36
  const cacheKey = `${key}_${JSON.stringify(labels)}`;
31
37
  const cacheValue = this.settingsCache.get(cacheKey);
32
38
  if (cacheValue !== undefined) {
39
+ if (watingToNetwork === cacheValue) {
40
+ return new Promise((resolve) => {
41
+ this.networkEvents.once(cacheKey, (networkValue) => {
42
+ resolve(SettingsManager.readNetworkValue(networkValue, defaultValue));
43
+ });
44
+ });
45
+ }
33
46
  return cacheValue;
34
47
  }
35
48
 
@@ -39,6 +52,7 @@ module.exports = class SettingsManager {
39
52
 
40
53
  let networkValue;
41
54
  try {
55
+ this.settingsCache.set(cacheKey, watingToNetwork, this.ttl);
42
56
  const networkReponse = await this.network.get(`/api/v1/settings/get-setting/${key}`, {
43
57
  params: {
44
58
  labels,
@@ -50,7 +64,8 @@ module.exports = class SettingsManager {
50
64
  logger.error('Cant get setting from network');
51
65
  }
52
66
 
53
- const returnValue = typeof networkValue !== 'undefined' ? networkValue : defaultValue;
67
+ this.networkEvents.emit(cacheKey, networkValue);
68
+ const returnValue = SettingsManager.readNetworkValue(networkValue, defaultValue);
54
69
  this.settingsCache.set(cacheKey, returnValue, this.ttl);
55
70
  return returnValue;
56
71
  }
@@ -72,6 +72,23 @@ describe('Settings', () => {
72
72
  expect(value2).toEqual('value1');
73
73
  });
74
74
 
75
+
76
+ it('Use only one request for similar keys', async () => {
77
+ const m = mockSetting('key1EM', 'value1EM');
78
+ const settings = new Settings({
79
+ serviceUrl: `http://${serviceUrl}/`,
80
+ });
81
+
82
+ const [value, value2] = await Promise.all([
83
+ settings.get('key1EM', 'dv'),
84
+ settings.get('key1EM', 'dv'),
85
+ ]);
86
+ expect(value).toEqual('value1EM');
87
+ expect(m.isDone()).toBeTruthy();
88
+
89
+ expect(value2).toEqual('value1EM');
90
+ });
91
+
75
92
  it('Finds with labels', async () => {
76
93
  const m = mockSetting('key1', 'value1', [{ fleetId: 'uuid' }]);
77
94
  const settings = new Settings({