@itentialopensource/adapter-adtran_mosaic_devicemanager 0.1.1

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.
Files changed (69) hide show
  1. package/.eslintignore +5 -0
  2. package/.eslintrc.js +18 -0
  3. package/.jshintrc +3 -0
  4. package/CHANGELOG.md +9 -0
  5. package/CODE_OF_CONDUCT.md +48 -0
  6. package/CONTRIBUTING.md +158 -0
  7. package/ENHANCE.md +69 -0
  8. package/LICENSE +201 -0
  9. package/PROPERTIES.md +247 -0
  10. package/README.md +257 -0
  11. package/SUMMARY.md +9 -0
  12. package/TROUBLESHOOT.md +46 -0
  13. package/adapter.js +9118 -0
  14. package/adapterBase.js +1299 -0
  15. package/entities/.generic/action.json +109 -0
  16. package/entities/.generic/schema.json +23 -0
  17. package/entities/.system/action.json +50 -0
  18. package/entities/.system/mockdatafiles/getToken-default.json +3 -0
  19. package/entities/.system/mockdatafiles/healthcheck-default.json +3 -0
  20. package/entities/.system/schema.json +19 -0
  21. package/entities/.system/schemaTokenReq.json +53 -0
  22. package/entities/.system/schemaTokenResp.json +53 -0
  23. package/entities/DeviceAPI/action.json +1030 -0
  24. package/entities/DeviceAPI/mockdatafiles/configureDeviceLoggingLevel-default.json +3 -0
  25. package/entities/DeviceAPI/mockdatafiles/createDeviceAttributes-default.json +3 -0
  26. package/entities/DeviceAPI/mockdatafiles/createDevicePOST-default.json +4 -0
  27. package/entities/DeviceAPI/mockdatafiles/deviceTraceLevel-default.json +3 -0
  28. package/entities/DeviceAPI/mockdatafiles/modifyDeviceAttributes-default.json +3 -0
  29. package/entities/DeviceAPI/mockdatafiles/requestDeviceAttributeRefresh-default.json +4 -0
  30. package/entities/DeviceAPI/schema.json +68 -0
  31. package/entities/SubscriberAPI/action.json +901 -0
  32. package/entities/SubscriberAPI/mockdatafiles/deleteSubscriberAttributes-default.json +6 -0
  33. package/entities/SubscriberAPI/mockdatafiles/getUserRoles-default.json +4 -0
  34. package/entities/SubscriberAPI/mockdatafiles/modifySubscriber-default.json +4 -0
  35. package/entities/SubscriberAPI/mockdatafiles/statisticsForSpecificSubscriber-default.json +5 -0
  36. package/entities/SubscriberAPI/mockdatafiles/statisticsForSubscribers-default.json +3 -0
  37. package/entities/SubscriberAPI/schema.json +73 -0
  38. package/error.json +190 -0
  39. package/package.json +87 -0
  40. package/pronghorn.json +4935 -0
  41. package/propertiesDecorators.json +14 -0
  42. package/propertiesSchema.json +1204 -0
  43. package/refs?service=git-upload-pack +0 -0
  44. package/report/creationReport.json +599 -0
  45. package/report/openapi.json +7211 -0
  46. package/report/updateReport1651531040781.json +114 -0
  47. package/sampleProperties.json +106 -0
  48. package/test/integration/adapterTestBasicGet.js +85 -0
  49. package/test/integration/adapterTestConnectivity.js +93 -0
  50. package/test/integration/adapterTestIntegration.js +3582 -0
  51. package/test/unit/adapterBaseTestUnit.js +942 -0
  52. package/test/unit/adapterTestUnit.js +5053 -0
  53. package/utils/addAuth.js +94 -0
  54. package/utils/artifactize.js +146 -0
  55. package/utils/basicGet.js +50 -0
  56. package/utils/checkMigrate.js +63 -0
  57. package/utils/entitiesToDB.js +224 -0
  58. package/utils/findPath.js +74 -0
  59. package/utils/modify.js +154 -0
  60. package/utils/packModificationScript.js +35 -0
  61. package/utils/patches2bundledDeps.js +90 -0
  62. package/utils/pre-commit.sh +27 -0
  63. package/utils/removeHooks.js +20 -0
  64. package/utils/setup.js +33 -0
  65. package/utils/tbScript.js +169 -0
  66. package/utils/tbUtils.js +464 -0
  67. package/utils/testRunner.js +298 -0
  68. package/utils/troubleshootingAdapter.js +190 -0
  69. package/workflows/README.md +3 -0
package/adapterBase.js ADDED
@@ -0,0 +1,1299 @@
1
+ /* @copyright Itential, LLC 2018-9 */
2
+
3
+ // Set globals
4
+ /* global log */
5
+ /* eslint class-methods-use-this:warn */
6
+ /* eslint import/no-dynamic-require: warn */
7
+ /* eslint no-loop-func: warn */
8
+ /* eslint no-cond-assign: warn */
9
+ /* eslint global-require: warn */
10
+ /* eslint no-unused-vars: warn */
11
+ /* eslint prefer-destructuring: warn */
12
+
13
+ /* Required libraries. */
14
+ const fs = require('fs-extra');
15
+ const path = require('path');
16
+ const EventEmitterCl = require('events').EventEmitter;
17
+ const { execSync } = require('child_process');
18
+
19
+ /* The schema validator */
20
+ const AjvCl = require('ajv');
21
+
22
+ /* Fetch in the other needed components for the this Adaptor */
23
+ const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
24
+ const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHandler;
25
+
26
+ const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
27
+ const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
28
+ const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
29
+
30
+ let propUtil = null;
31
+
32
+ /*
33
+ * INTERNAL FUNCTION: force fail the adapter - generally done to cause restart
34
+ */
35
+ function forceFail(packChg) {
36
+ if (packChg !== undefined && packChg !== null && packChg === true) {
37
+ execSync(`rm -rf ${__dirname}/node modules`, { encoding: 'utf-8' });
38
+ execSync(`rm -rf ${__dirname}/package-lock.json`, { encoding: 'utf-8' });
39
+ execSync('npm install', { encoding: 'utf-8' });
40
+ }
41
+ log.error('NEED TO RESTART ADAPTER - FORCE FAIL');
42
+ const errorObj = {
43
+ origin: 'adapter-forceFail',
44
+ type: 'Force Fail so adapter will restart',
45
+ vars: []
46
+ };
47
+ setTimeout(() => {
48
+ throw new Error(JSON.stringify(errorObj));
49
+ }, 1000);
50
+ }
51
+
52
+ /*
53
+ * INTERNAL FUNCTION: update the action.json
54
+ */
55
+ function updateAction(entityPath, action, changes) {
56
+ // if the action file does not exist - error
57
+ const actionFile = path.join(entityPath, '/action.json');
58
+ if (!fs.existsSync(actionFile)) {
59
+ return 'Missing Action File';
60
+ }
61
+
62
+ // read in the file as a json object
63
+ const ajson = require(path.resolve(entityPath, 'action.json'));
64
+ let chgAct = {};
65
+
66
+ // get the action we need to change
67
+ for (let a = 0; a < ajson.actions.length; a += 1) {
68
+ if (ajson.actions[a].name === action) {
69
+ chgAct = ajson.actions[a];
70
+ break;
71
+ }
72
+ }
73
+ // merge the changes into the desired action
74
+ chgAct = propUtil.mergeProperties(changes, chgAct);
75
+
76
+ fs.writeFileSync(actionFile, JSON.stringify(ajson, null, 2));
77
+ return null;
78
+ }
79
+
80
+ /*
81
+ * INTERNAL FUNCTION: update the schema file
82
+ */
83
+ function updateSchema(entityPath, configFile, changes) {
84
+ // if the schema file does not exist - error
85
+ const schemaFile = path.join(entityPath, `/${configFile}`);
86
+ if (!fs.existsSync(schemaFile)) {
87
+ return 'Missing Schema File';
88
+ }
89
+
90
+ // read in the file as a json object
91
+ let schema = require(path.resolve(entityPath, configFile));
92
+
93
+ // merge the changes into the schema file
94
+ schema = propUtil.mergeProperties(changes, schema);
95
+
96
+ fs.writeFileSync(schemaFile, JSON.stringify(schema, null, 2));
97
+ return null;
98
+ }
99
+
100
+ /*
101
+ * INTERNAL FUNCTION: update the mock data file
102
+ */
103
+ function updateMock(mockPath, configFile, changes) {
104
+ // if the mock file does not exist - create it
105
+ const mockFile = path.join(mockPath, `/${configFile}`);
106
+ if (!fs.existsSync(mockFile)) {
107
+ const newMock = {};
108
+ fs.writeFileSync(mockFile, JSON.stringify(newMock, null, 2));
109
+ }
110
+
111
+ // read in the file as a json object
112
+ let mock = require(path.resolve(mockPath, configFile));
113
+
114
+ // merge the changes into the mock file
115
+ mock = propUtil.mergeProperties(changes, mock);
116
+
117
+ fs.writeFileSync(mockFile, JSON.stringify(mock, null, 2));
118
+ return null;
119
+ }
120
+
121
+ /*
122
+ * INTERNAL FUNCTION: update the package dependencies
123
+ */
124
+ function updatePackage(changes) {
125
+ // if the schema file does not exist - error
126
+ const packFile = path.join(__dirname, '/package.json');
127
+ if (!fs.existsSync(packFile)) {
128
+ return 'Missing Pacakge File';
129
+ }
130
+
131
+ // read in the file as a json object
132
+ const pack = require(path.resolve(__dirname, 'package.json'));
133
+
134
+ // only certain changes are allowed
135
+ if (changes.dependencies) {
136
+ const keys = Object.keys(changes.dependencies);
137
+
138
+ for (let k = 0; k < keys.length; k += 1) {
139
+ pack.dependencies[keys[k]] = changes.dependencies[keys[k]];
140
+ }
141
+ }
142
+
143
+ fs.writeFileSync(packFile, JSON.stringify(pack, null, 2));
144
+ return null;
145
+ }
146
+
147
+ /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
148
+ /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
149
+ class AdapterBase extends EventEmitterCl {
150
+ /**
151
+ * [System] Adapter
152
+ * @constructor
153
+ */
154
+ constructor(prongid, properties) {
155
+ // Instantiate the EventEmitter super class
156
+ super();
157
+
158
+ // IAP home directory injected by core when running the adapter within IAP
159
+ process.env.iap_home = process.argv[3];
160
+
161
+ try {
162
+ // Capture the adapter id
163
+ this.id = prongid;
164
+ this.propUtilInst = new PropUtilCl(prongid, __dirname);
165
+ propUtil = this.propUtilInst;
166
+ this.initProps = properties;
167
+ this.alive = false;
168
+ this.healthy = false;
169
+ this.suspended = false;
170
+ this.suspendMode = 'pause';
171
+ this.caching = false;
172
+ this.repeatCacheCount = 0;
173
+ this.allowFailover = 'AD.300';
174
+ this.noFailover = 'AD.500';
175
+
176
+ // set up the properties I care about
177
+ this.refreshProperties(properties);
178
+
179
+ // Instantiate the other components for this Adapter
180
+ this.requestHandlerInst = new RequestHandlerCl(this.id, this.allProps, __dirname);
181
+ } catch (e) {
182
+ // handle any exception
183
+ const origin = `${this.id}-adapterBase-constructor`;
184
+ log.error(`${origin}: Adapter may not have started properly. ${e}`);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * @callback healthCallback
190
+ * @param {Object} result - the result of the get request (contains an id and a status)
191
+ */
192
+ /**
193
+ * @callback getCallback
194
+ * @param {Object} result - the result of the get request (entity/ies)
195
+ * @param {String} error - any error that occured
196
+ */
197
+ /**
198
+ * @callback createCallback
199
+ * @param {Object} item - the newly created entity
200
+ * @param {String} error - any error that occured
201
+ */
202
+ /**
203
+ * @callback updateCallback
204
+ * @param {String} status - the status of the update action
205
+ * @param {String} error - any error that occured
206
+ */
207
+ /**
208
+ * @callback deleteCallback
209
+ * @param {String} status - the status of the delete action
210
+ * @param {String} error - any error that occured
211
+ */
212
+
213
+ /**
214
+ * refreshProperties is used to set up all of the properties for the connector.
215
+ * It allows properties to be changed later by simply calling refreshProperties rather
216
+ * than having to restart the connector.
217
+ *
218
+ * @function refreshProperties
219
+ * @param {Object} properties - an object containing all of the properties
220
+ * @param {boolean} init - are we initializing -- is so no need to refresh throtte engine
221
+ */
222
+ refreshProperties(properties) {
223
+ const meth = 'adapterBase-refreshProperties';
224
+ const origin = `${this.id}-${meth}`;
225
+ log.trace(origin);
226
+
227
+ try {
228
+ // Read the properties schema from the file system
229
+ const propertiesSchema = JSON.parse(fs.readFileSync(path.join(__dirname, 'propertiesSchema.json'), 'utf-8'));
230
+
231
+ // add any defaults to the data
232
+ const defProps = this.propUtilInst.setDefaults(propertiesSchema);
233
+ this.allProps = this.propUtilInst.mergeProperties(properties, defProps);
234
+
235
+ // validate the entity against the schema
236
+ const ajvInst = new AjvCl();
237
+ const validate = ajvInst.compile(propertiesSchema);
238
+ const result = validate(this.allProps);
239
+
240
+ // if invalid properties throw an error
241
+ if (!result) {
242
+ if (this.requestHandlerInst) {
243
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Properties', [JSON.stringify(validate.errors)], null, null, null);
244
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
245
+ throw new Error(JSON.stringify(errorObj));
246
+ } else {
247
+ log.error(`${origin}: ${JSON.stringify(validate.errors)}`);
248
+ throw new Error(`${origin}: ${JSON.stringify(validate.errors)}`);
249
+ }
250
+ }
251
+
252
+ // properties that this code cares about
253
+ this.healthcheckType = this.allProps.healthcheck.type;
254
+ this.healthcheckInterval = this.allProps.healthcheck.frequency;
255
+ this.healthcheckQuery = this.allProps.healthcheck.query_object;
256
+
257
+ // set the failover codes from properties
258
+ if (this.allProps.request.failover_codes) {
259
+ if (Array.isArray(this.allProps.request.failover_codes)) {
260
+ this.failoverCodes = this.allProps.request.failover_codes;
261
+ } else {
262
+ this.failoverCodes = [this.allProps.request.failover_codes];
263
+ }
264
+ } else {
265
+ this.failoverCodes = [];
266
+ }
267
+
268
+ // set the caching flag from properties
269
+ if (this.allProps.cache_location) {
270
+ if (this.allProps.cache_location === 'redis' || this.allProps.cache_location === 'local') {
271
+ this.caching = true;
272
+ }
273
+ }
274
+
275
+ // if this is truly a refresh and we have a request handler, refresh it
276
+ if (this.requestHandlerInst) {
277
+ this.requestHandlerInst.refreshProperties(properties);
278
+ }
279
+ } catch (e) {
280
+ log.error(`${origin}: Properties may not have been set properly. ${e}`);
281
+ }
282
+ }
283
+
284
+ /**
285
+ * @summary Connect function is used during Pronghorn startup to provide instantiation feedback.
286
+ *
287
+ * @function connect
288
+ */
289
+ connect() {
290
+ const origin = `${this.id}-adapterBase-connect`;
291
+ log.trace(origin);
292
+
293
+ // initially set as off
294
+ this.emit('OFFLINE', { id: this.id });
295
+ this.alive = true;
296
+
297
+ // if there is no healthcheck just change the emit to ONLINE
298
+ // We do not recommend no healthcheck!!!
299
+ if (this.healthcheckType === 'none') {
300
+ log.error(`${origin}: Waiting 1 Seconds to emit Online`);
301
+ setTimeout(() => {
302
+ this.emit('ONLINE', { id: this.id });
303
+ this.healthy = true;
304
+ }, 1000);
305
+ }
306
+
307
+ // is the healthcheck only suppose to run on startup
308
+ // (intermittent runs on startup and after that)
309
+ if (this.healthcheckType === 'startup' || this.healthcheckType === 'intermittent') {
310
+ // run an initial healthcheck
311
+ this.healthCheck(null, (status) => {
312
+ log.spam(`${origin}: ${status}`);
313
+ });
314
+ }
315
+
316
+ // is the healthcheck suppose to run intermittently
317
+ if (this.healthcheckType === 'intermittent') {
318
+ // run the healthcheck in an interval
319
+ setInterval(() => {
320
+ // try to see if mongo is available
321
+ this.healthCheck(null, (status) => {
322
+ log.spam(`${origin}: ${status}`);
323
+ });
324
+ }, this.healthcheckInterval);
325
+ }
326
+ }
327
+
328
+ /**
329
+ * @summary HealthCheck function is used to provide Pronghorn the status of this adapter.
330
+ *
331
+ * @function healthCheck
332
+ */
333
+ healthCheck(reqObj, callback) {
334
+ const origin = `${this.id}-adapterBase-healthCheck`;
335
+ log.trace(origin);
336
+
337
+ // if there is healthcheck query_object property, it needs to be added to the adapter
338
+ let myRequest = reqObj;
339
+ if (this.healthcheckQuery && Object.keys(this.healthcheckQuery).length > 0) {
340
+ if (myRequest && myRequest.uriQuery) {
341
+ myRequest.uriQuery = { ...myRequest.uriQuery, ...this.healthcheckQuery };
342
+ } else if (myRequest) {
343
+ myRequest.uriQuery = this.healthcheckQuery;
344
+ } else {
345
+ myRequest = {
346
+ uriQuery: this.healthcheckQuery
347
+ };
348
+ }
349
+ }
350
+
351
+ // call to the healthcheck in connector
352
+ return this.requestHandlerInst.identifyHealthcheck(myRequest, (res, error) => {
353
+ // unhealthy
354
+ if (error) {
355
+ // if we were healthy, toggle health
356
+ if (this.healthy) {
357
+ this.emit('OFFLINE', { id: this.id });
358
+ this.emit('DEGRADED', { id: this.id });
359
+ this.healthy = false;
360
+ log.error(`${origin}: HEALTH CHECK - Error ${error}`);
361
+ } else {
362
+ // still log but set the level to trace
363
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${error}`);
364
+ }
365
+
366
+ return callback(false);
367
+ }
368
+
369
+ // if we were unhealthy, toggle health
370
+ if (!this.healthy) {
371
+ this.emit('FIXED', { id: this.id });
372
+ this.emit('ONLINE', { id: this.id });
373
+ this.healthy = true;
374
+ log.info(`${origin}: HEALTH CHECK SUCCESSFUL`);
375
+ } else {
376
+ // still log but set the level to trace
377
+ log.trace(`${origin}: HEALTH CHECK STILL SUCCESSFUL`);
378
+ }
379
+
380
+ return callback(true);
381
+ });
382
+ }
383
+
384
+ /**
385
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
386
+ * @param {array} ignoreThese - additional methods to ignore (optional)
387
+ *
388
+ * @function iapGetAdapterWorkflowFunctions
389
+ */
390
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
391
+ const myfunctions = this.getAllFunctions();
392
+ const wffunctions = [];
393
+
394
+ // remove the functions that should not be in a Workflow
395
+ for (let m = 0; m < myfunctions.length; m += 1) {
396
+ if (myfunctions[m] === 'addEntityCache') {
397
+ // got to the second tier (adapterBase)
398
+ break;
399
+ }
400
+ if (myfunctions[m] !== 'iapHasAdapterEntity' && myfunctions[m] !== 'iapVerifyAdapterCapability'
401
+ && myfunctions[m] !== 'iapUpdateAdapterEntityCache' && myfunctions[m] !== 'healthCheck'
402
+ && myfunctions[m] !== 'iapGetAdapterWorkflowFunctions'
403
+ && !(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
404
+ let found = false;
405
+ if (ignoreThese && Array.isArray(ignoreThese)) {
406
+ for (let i = 0; i < ignoreThese.length; i += 1) {
407
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
408
+ found = true;
409
+ }
410
+ }
411
+ }
412
+ if (!found) {
413
+ wffunctions.push(myfunctions[m]);
414
+ }
415
+ }
416
+ }
417
+
418
+ return wffunctions;
419
+ }
420
+
421
+ /**
422
+ * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This
423
+ * allows customers to make changes to adapter configuration without having to be on the
424
+ * file system.
425
+ *
426
+ * @function iapUpdateAdapterConfiguration
427
+ * @param {string} configFile - the name of the file being updated (required)
428
+ * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
429
+ * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
430
+ * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
431
+ * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
432
+ * @param {Callback} callback - The results of the call
433
+ */
434
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
435
+ const meth = 'adapterBase-iapUpdateAdapterConfiguration';
436
+ const origin = `${this.id}-${meth}`;
437
+ log.trace(origin);
438
+
439
+ // verify the parameters are valid
440
+ if (changes === undefined || changes === null || typeof changes !== 'object'
441
+ || Object.keys(changes).length === 0) {
442
+ const result = {
443
+ response: 'No configuration updates to make'
444
+ };
445
+ log.info(result.response);
446
+ return callback(result, null);
447
+ }
448
+ if (configFile === undefined || configFile === null || configFile === '') {
449
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
450
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
451
+ return callback(null, errorObj);
452
+ }
453
+
454
+ // take action based on configFile being changed
455
+ if (configFile === 'package.json') {
456
+ const pres = updatePackage(changes);
457
+ if (pres) {
458
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
459
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
460
+ return callback(null, errorObj);
461
+ }
462
+ const result = {
463
+ response: 'Package updates completed - restarting adapter'
464
+ };
465
+ log.info(result.response);
466
+ forceFail(true);
467
+ return callback(result, null);
468
+ }
469
+ if (entity === undefined || entity === null || entity === '') {
470
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
471
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
472
+ return callback(null, errorObj);
473
+ }
474
+
475
+ // this means we are changing an entity file so type is required
476
+ if (type === undefined || type === null || type === '') {
477
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
478
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
479
+ return callback(null, errorObj);
480
+ }
481
+
482
+ // if the entity does not exist - error
483
+ const epath = `${__dirname}/entities/${entity}`;
484
+ if (!fs.existsSync(epath)) {
485
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
486
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
487
+ return callback(null, errorObj);
488
+ }
489
+
490
+ // take action based on type of file being changed
491
+ if (type === 'action') {
492
+ // BACKUP???
493
+ const ares = updateAction(epath, action, changes);
494
+ if (ares) {
495
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
496
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
497
+ return callback(null, errorObj);
498
+ }
499
+ // AJV CHECK???
500
+ // RESTORE IF NEEDED???
501
+ const result = {
502
+ response: `Action updates completed to entity: ${entity} - ${action}`
503
+ };
504
+ log.info(result.response);
505
+ return callback(result, null);
506
+ }
507
+ if (type === 'schema') {
508
+ const sres = updateSchema(epath, configFile, changes);
509
+ if (sres) {
510
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
511
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
512
+ return callback(null, errorObj);
513
+ }
514
+ const result = {
515
+ response: `Schema updates completed to entity: ${entity} - ${configFile}`
516
+ };
517
+ log.info(result.response);
518
+ return callback(result, null);
519
+ }
520
+ if (type === 'mock') {
521
+ // if the mock directory does not exist - error
522
+ const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
523
+ if (!fs.existsSync(mpath)) {
524
+ fs.mkdirSync(mpath);
525
+ }
526
+
527
+ const mres = updateMock(mpath, configFile, changes);
528
+ if (mres) {
529
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
530
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
531
+ return callback(null, errorObj);
532
+ }
533
+ const result = {
534
+ response: `Mock data updates completed to entity: ${entity} - ${configFile}`
535
+ };
536
+ log.info(result.response);
537
+ return callback(result, null);
538
+ }
539
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
540
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
541
+ return callback(null, errorObj);
542
+ }
543
+
544
+ /**
545
+ * See if the API path provided is found in this adapter
546
+ *
547
+ * @function iapFindAdapterPath
548
+ * @param {string} apiPath - the api path to check on
549
+ * @param {Callback} callback - The results of the call
550
+ */
551
+ iapFindAdapterPath(apiPath, callback) {
552
+ const result = {
553
+ apiPath
554
+ };
555
+
556
+ // verify the path was provided
557
+ if (!apiPath) {
558
+ log.error('NO API PATH PROVIDED!');
559
+ result.found = false;
560
+ result.message = 'NO PATH PROVIDED!';
561
+ return callback(null, result);
562
+ }
563
+
564
+ // make sure the entities directory exists
565
+ const entitydir = path.join(__dirname, 'entities');
566
+ if (!fs.statSync(entitydir).isDirectory()) {
567
+ log.error('Could not find the entities directory');
568
+ result.found = false;
569
+ result.message = 'Could not find the entities directory';
570
+ return callback(null, result);
571
+ }
572
+
573
+ const entities = fs.readdirSync(entitydir);
574
+ const fitems = [];
575
+
576
+ // need to go through each entity in the entities directory
577
+ for (let e = 0; e < entities.length; e += 1) {
578
+ // make sure the entity is a directory - do not care about extra files
579
+ // only entities (dir)
580
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
581
+ // see if the action file exists in the entity
582
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
583
+ // Read the entity actions from the file system
584
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
585
+
586
+ // go through all of the actions set the appropriate info in the newActions
587
+ for (let a = 0; a < actions.actions.length; a += 1) {
588
+ if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
589
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
590
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
591
+ const fitem = {
592
+ entity: entities[e],
593
+ action: actions.actions[a].name,
594
+ method: actions.actions[a].method,
595
+ path: actions.actions[a].entitypath
596
+ };
597
+ fitems.push(fitem);
598
+ }
599
+ }
600
+ } else {
601
+ log.error(`Could not find entities ${entities[e]} action.json file`);
602
+ result.found = false;
603
+ result.message = `Could not find entities ${entities[e]} action.json file`;
604
+ return callback(null, result);
605
+ }
606
+ } else {
607
+ log.error(`Could not find entities ${entities[e]} directory`);
608
+ result.found = false;
609
+ result.message = `Could not find entities ${entities[e]} directory`;
610
+ return callback(null, result);
611
+ }
612
+ }
613
+
614
+ if (fitems.length === 0) {
615
+ log.info('PATH NOT FOUND!');
616
+ result.found = false;
617
+ result.message = 'API PATH NOT FOUND!';
618
+ return callback(null, result);
619
+ }
620
+
621
+ result.foundIn = fitems;
622
+ result.found = true;
623
+ result.message = 'API PATH FOUND!';
624
+ return callback(result, null);
625
+ }
626
+
627
+ /**
628
+ * @summary Suspends the adapter
629
+ * @param {Callback} callback - The adapater suspension status
630
+ * @function iapSuspendAdapter
631
+ */
632
+ iapSuspendAdapter(mode, callback) {
633
+ const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
634
+ if (this.suspended) {
635
+ throw new Error(`${origin}: Adapter is already suspended`);
636
+ }
637
+ try {
638
+ this.suspended = true;
639
+ this.suspendMode = mode;
640
+ if (this.suspendMode === 'pause') {
641
+ const props = JSON.parse(JSON.stringify(this.initProps));
642
+ // To suspend adapter, enable throttling and set concurrent max to 0
643
+ props.throttle.throttle_enabled = true;
644
+ props.throttle.concurrent_max = 0;
645
+ this.refreshProperties(props);
646
+ }
647
+ return callback({ suspended: true });
648
+ } catch (error) {
649
+ return callback(null, error);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * @summary Unsuspends the adapter
655
+ * @param {Callback} callback - The adapater suspension status
656
+ *
657
+ * @function iapUnsuspendAdapter
658
+ */
659
+ iapUnsuspendAdapter(callback) {
660
+ const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
661
+ if (!this.suspended) {
662
+ throw new Error(`${origin}: Adapter is not suspended`);
663
+ }
664
+ if (this.suspendMode === 'pause') {
665
+ const props = JSON.parse(JSON.stringify(this.initProps));
666
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
667
+ props.throttle.throttle_enabled = true;
668
+ props.throttle.concurrent_max = 1;
669
+ this.refreshProperties(props);
670
+ setTimeout(() => {
671
+ this.getQueue((q, error) => {
672
+ // console.log("Items in queue: " + String(q.length))
673
+ if (q.length === 0) {
674
+ // if queue is empty, return to initial properties state
675
+ this.refreshProperties(this.initProps);
676
+ this.suspended = false;
677
+ return callback({ suspended: false });
678
+ }
679
+ // recursive call to check queue again every second
680
+ return this.iapUnsuspendAdapter(callback);
681
+ });
682
+ }, 1000);
683
+ } else {
684
+ this.suspended = false;
685
+ callback({ suspend: false });
686
+ }
687
+ }
688
+
689
+ /**
690
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
691
+ *
692
+ * @function iapGetAdapterQueue
693
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
694
+ */
695
+ iapGetAdapterQueue(callback) {
696
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
697
+ log.trace(origin);
698
+
699
+ return this.requestHandlerInst.getQueue(callback);
700
+ }
701
+
702
+ /**
703
+ * @summary runs troubleshoot scripts for adapter
704
+ *
705
+ * @function iapTroubleshootAdapter
706
+ * @param {Object} props - the connection, healthcheck and authentication properties
707
+ * @param {boolean} persistFlag - whether the adapter properties should be updated
708
+ * @param {Adapter} adapter - adapter instance to troubleshoot
709
+ * @param {Callback} callback - callback function to return troubleshoot results
710
+ */
711
+ async iapTroubleshootAdapter(props, persistFlag, adapter, callback) {
712
+ try {
713
+ const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
714
+ if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
715
+ return callback(result);
716
+ }
717
+ return callback(null, result);
718
+ } catch (error) {
719
+ return callback(null, error);
720
+ }
721
+ }
722
+
723
+ /**
724
+ * @summary runs healthcheck script for adapter
725
+ *
726
+ * @function iapRunAdapterHealthcheck
727
+ * @param {Adapter} adapter - adapter instance to troubleshoot
728
+ * @param {Callback} callback - callback function to return healthcheck status
729
+ */
730
+ async iapRunAdapterHealthcheck(adapter, callback) {
731
+ try {
732
+ const result = await tbUtils.healthCheck(adapter);
733
+ if (result) {
734
+ return callback(result);
735
+ }
736
+ return callback(null, result);
737
+ } catch (error) {
738
+ return callback(null, error);
739
+ }
740
+ }
741
+
742
+ /**
743
+ * @summary runs connectivity check script for adapter
744
+ *
745
+ * @function iapRunAdapterConnectivity
746
+ * @param {Adapter} adapter - adapter instance to troubleshoot
747
+ * @param {Callback} callback - callback function to return connectivity status
748
+ */
749
+ async iapRunAdapterConnectivity(callback) {
750
+ try {
751
+ const { serviceItem } = await tbUtils.getAdapterConfig();
752
+ const { host } = serviceItem.properties.properties;
753
+ const result = tbUtils.runConnectivity(host, false);
754
+ if (result.failCount > 0) {
755
+ return callback(null, result);
756
+ }
757
+ return callback(result);
758
+ } catch (error) {
759
+ return callback(null, error);
760
+ }
761
+ }
762
+
763
+ /**
764
+ * @summary runs basicGet script for adapter
765
+ *
766
+ * @function iapRunAdapterBasicGet
767
+ * @param {Callback} callback - callback function to return basicGet result
768
+ */
769
+ iapRunAdapterBasicGet(callback) {
770
+ try {
771
+ const result = tbUtils.runBasicGet(false);
772
+ if (result.failCount > 0) {
773
+ return callback(null, result);
774
+ }
775
+ return callback(result);
776
+ } catch (error) {
777
+ return callback(null, error);
778
+ }
779
+ }
780
+
781
+ /**
782
+ * @summary moves entities to mongo database
783
+ *
784
+ * @function iapMoveAdapterEntitiesToDB
785
+ *
786
+ * @return {Callback} - containing the response from the mongo transaction
787
+ */
788
+ iapMoveAdapterEntitiesToDB(callback) {
789
+ const meth = 'adapterBase-iapMoveAdapterEntitiesToDB';
790
+ const origin = `${this.id}-${meth}`;
791
+ log.trace(origin);
792
+
793
+ try {
794
+ return callback(entitiesToDB.iapMoveAdapterEntitiesToDB(__dirname, { pronghornProps: this.allProps, id: this.id }), null);
795
+ } catch (err) {
796
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, err);
797
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
798
+ return callback(null, errorObj);
799
+ }
800
+ }
801
+
802
+ /**
803
+ * getAllFunctions is used to get all of the exposed function in the adapter
804
+ *
805
+ * @function getAllFunctions
806
+ */
807
+ getAllFunctions() {
808
+ let myfunctions = [];
809
+ let obj = this;
810
+
811
+ // find the functions in this class
812
+ do {
813
+ const l = Object.getOwnPropertyNames(obj)
814
+ .concat(Object.getOwnPropertySymbols(obj).map((s) => s.toString()))
815
+ .sort()
816
+ .filter((p, i, arr) => typeof obj[p] === 'function' && p !== 'constructor' && (i === 0 || p !== arr[i - 1]) && myfunctions.indexOf(p) === -1);
817
+ myfunctions = myfunctions.concat(l);
818
+ }
819
+ while (
820
+ (obj = Object.getPrototypeOf(obj)) && Object.getPrototypeOf(obj)
821
+ );
822
+
823
+ return myfunctions;
824
+ }
825
+
826
+ /**
827
+ * checkActionFiles is used to update the validation of the action files.
828
+ *
829
+ * @function checkActionFiles
830
+ */
831
+ checkActionFiles() {
832
+ const origin = `${this.id}-adapterBase-checkActionFiles`;
833
+ log.trace(origin);
834
+
835
+ // validate the action files for the adapter
836
+ try {
837
+ return this.requestHandlerInst.checkActionFiles();
838
+ } catch (e) {
839
+ return ['Exception increase log level'];
840
+ }
841
+ }
842
+
843
+ /**
844
+ * checkProperties is used to validate the adapter properties.
845
+ *
846
+ * @function checkProperties
847
+ * @param {Object} properties - an object containing all of the properties
848
+ */
849
+ checkProperties(properties) {
850
+ const origin = `${this.myid}-adapterBase-checkProperties`;
851
+ log.trace(origin);
852
+
853
+ // validate the properties for the adapter
854
+ try {
855
+ return this.requestHandlerInst.checkProperties(properties);
856
+ } catch (e) {
857
+ return { exception: 'Exception increase log level' };
858
+ }
859
+ }
860
+
861
+ /**
862
+ * @summary Takes in property text and an encoding/encryption and returns the resulting
863
+ * encoded/encrypted string
864
+ *
865
+ * @function encryptProperty
866
+ * @param {String} property - the property to encrypt
867
+ * @param {String} technique - the technique to use to encrypt
868
+ *
869
+ * @param {Callback} callback - a callback function to return the result
870
+ * Encrypted String or the Error
871
+ */
872
+ encryptProperty(property, technique, callback) {
873
+ const origin = `${this.id}-adapterBase-encryptProperty`;
874
+ log.trace(origin);
875
+
876
+ // Make the call -
877
+ // encryptProperty(property, technique, callback)
878
+ return this.requestHandlerInst.encryptProperty(property, technique, callback);
879
+ }
880
+
881
+ /**
882
+ * @summary take the entities and add them to the cache
883
+ *
884
+ * @function addEntityCache
885
+ * @param {String} entityType - the type of the entities
886
+ * @param {Array} data - the list of entities
887
+ * @param {String} key - unique key for the entities
888
+ *
889
+ * @param {Callback} callback - An array of whether the adapter can has the
890
+ * desired capability or an error
891
+ */
892
+ addEntityCache(entityType, entities, key, callback) {
893
+ const meth = 'adapterBase-addEntityCache';
894
+ const origin = `${this.id}-${meth}`;
895
+ log.trace(origin);
896
+
897
+ // list containing the items to add to the cache
898
+ const entityIds = [];
899
+
900
+ if (entities && Object.hasOwnProperty.call(entities, 'response')
901
+ && Array.isArray(entities.response)) {
902
+ for (let e = 0; e < entities.response.length; e += 1) {
903
+ entityIds.push(entities.response[e][key]);
904
+ }
905
+ }
906
+
907
+ // add the entities to the cache
908
+ return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
909
+ if (error) {
910
+ return callback(null, error);
911
+ }
912
+ if (!loaded) {
913
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
914
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
915
+ return callback(null, errorObj);
916
+ }
917
+
918
+ return callback(loaded);
919
+ });
920
+ }
921
+
922
+ /**
923
+ * @summary sees if the entity is in the entity list or not
924
+ *
925
+ * @function entityInList
926
+ * @param {String/Array} entityId - the specific entity we are looking for
927
+ * @param {Array} data - the list of entities
928
+ *
929
+ * @param {Callback} callback - An array of whether the adapter can has the
930
+ * desired capability or an error
931
+ */
932
+ entityInList(entityId, data) {
933
+ const origin = `${this.id}-adapterBase-entityInList`;
934
+ log.trace(origin);
935
+
936
+ // need to check on the entities that were passed in
937
+ if (Array.isArray(entityId)) {
938
+ const resEntity = [];
939
+
940
+ for (let e = 0; e < entityId.length; e += 1) {
941
+ if (data.includes(entityId[e])) {
942
+ resEntity.push(true);
943
+ } else {
944
+ resEntity.push(false);
945
+ }
946
+ }
947
+
948
+ return resEntity;
949
+ }
950
+
951
+ // does the entity list include the specific entity
952
+ return [data.includes(entityId)];
953
+ }
954
+
955
+ /**
956
+ * @summary prepare results for verify capability so they are true/false
957
+ *
958
+ * @function capabilityResults
959
+ * @param {Array} results - the results from the capability check
960
+ *
961
+ * @param {Callback} callback - An array of whether the adapter can has the
962
+ * desired capability or an error
963
+ */
964
+ capabilityResults(results, callback) {
965
+ const meth = 'adapterBase-capabilityResults';
966
+ const origin = `${this.id}-${meth}`;
967
+ log.trace(origin);
968
+ let locResults = results;
969
+
970
+ if (locResults && locResults[0] === 'needupdate') {
971
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', ['unknown'], null, null, null);
972
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
973
+ this.repeatCacheCount += 1;
974
+ return callback(null, errorObj);
975
+ }
976
+
977
+ // if an error occured, return the error
978
+ if (locResults && locResults[0] === 'error') {
979
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Error Verifying Entity Cache', null, null, null, null);
980
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
981
+ return callback(null, errorObj);
982
+ }
983
+
984
+ // go through the response and change to true/false
985
+ if (locResults) {
986
+ // if not an array, just convert the return
987
+ if (!Array.isArray(locResults)) {
988
+ if (locResults === 'found') {
989
+ locResults = [true];
990
+ } else {
991
+ locResults = [false];
992
+ }
993
+ } else {
994
+ const temp = [];
995
+
996
+ // go through each element in the array to convert
997
+ for (let r = 0; r < locResults.length; r += 1) {
998
+ if (locResults[r] === 'found') {
999
+ temp.push(true);
1000
+ } else {
1001
+ temp.push(false);
1002
+ }
1003
+ }
1004
+ locResults = temp;
1005
+ }
1006
+ }
1007
+
1008
+ // return the results
1009
+ return callback(locResults);
1010
+ }
1011
+
1012
+ /**
1013
+ * @summary Provides a way for the adapter to tell north bound integrations
1014
+ * all of the capabilities for the current adapter
1015
+ *
1016
+ * @function getAllCapabilities
1017
+ *
1018
+ * @return {Array} - containing the entities and the actions available on each entity
1019
+ */
1020
+ getAllCapabilities() {
1021
+ const origin = `${this.id}-adapterBase-getAllCapabilities`;
1022
+ log.trace(origin);
1023
+
1024
+ // validate the capabilities for the adapter
1025
+ try {
1026
+ return this.requestHandlerInst.getAllCapabilities();
1027
+ } catch (e) {
1028
+ return [];
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * @summary Make one of the needed Broker calls - could be one of many
1034
+ *
1035
+ * @function iapMakeBrokerCall
1036
+ * @param {string} brokCall - the name of the broker call (required)
1037
+ * @param {object} callProps - the proeprties for the broker call (required)
1038
+ * @param {object} devResp - the device details to extract needed inputs (required)
1039
+ * @param {string} filterName - any filter to search on (required)
1040
+ *
1041
+ * @param {getCallback} callback - a callback function to return the result of the call
1042
+ */
1043
+ iapMakeBrokerCall(brokCall, callProps, devResp, filterName, callback) {
1044
+ const meth = 'adapter-iapMakeBrokerCall';
1045
+ const origin = `${this.id}-${meth}`;
1046
+ log.trace(origin);
1047
+
1048
+ try {
1049
+ let uriPath = '';
1050
+ let uriMethod = 'GET';
1051
+ let callQuery = {};
1052
+ let callBody = {};
1053
+ let callHeaders = {};
1054
+ let handleFail = 'fail';
1055
+ let ostypePrefix = '';
1056
+ let statusValue = 'true';
1057
+ if (callProps.path) {
1058
+ uriPath = `${callProps.path}`;
1059
+
1060
+ // make any necessary changes to the path
1061
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1062
+ const rqKeys = Object.keys(callProps.requestFields);
1063
+
1064
+ // get the field from the provided device
1065
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1066
+ // get the request field we are retrieving
1067
+ const loopField = callProps.requestFields[rqKeys[rq]];
1068
+ const loopArray = loopField.split('.');
1069
+ let nestedValue = devResp;
1070
+
1071
+ // loops through incase the field is nested
1072
+ for (let i = 0; i < loopArray.length; i += 1) {
1073
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1074
+ nestedValue = nestedValue[loopArray[i]];
1075
+ } else {
1076
+ // failed to traverse
1077
+ nestedValue = loopField;
1078
+ break;
1079
+ }
1080
+ }
1081
+
1082
+ // put the value into the path - if it has been specified in the path
1083
+ uriPath = uriPath.replace(`{${rqKeys[rq]}}`, nestedValue);
1084
+ }
1085
+ }
1086
+ }
1087
+ if (callProps.method) {
1088
+ uriMethod = callProps.method;
1089
+ }
1090
+ if (callProps.query) {
1091
+ callQuery = callProps.query;
1092
+
1093
+ // go through the query params to check for variable values
1094
+ const cpKeys = Object.keys(callQuery);
1095
+ for (let cp = 0; cp < cpKeys.length; cp += 1) {
1096
+ if (callQuery[cpKeys[cp]].startsWith('{') && callQuery[cpKeys[cp]].endsWith('}')) {
1097
+ // make any necessary changes to the query params
1098
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1099
+ const rqKeys = Object.keys(callProps.requestFields);
1100
+
1101
+ // get the uuid from the device
1102
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1103
+ if (cpKeys[cp] === rqKeys[rq]) {
1104
+ // get the request field we are retrieving
1105
+ const loopField = callProps.requestFields[rqKeys[rq]];
1106
+ const loopArray = loopField.split('.');
1107
+ let nestedValue = devResp;
1108
+
1109
+ // loops through incase the field is nested
1110
+ for (let i = 0; i < loopArray.length; i += 1) {
1111
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1112
+ nestedValue = nestedValue[loopArray[i]];
1113
+ } else {
1114
+ // failed to traverse
1115
+ nestedValue = loopField;
1116
+ break;
1117
+ }
1118
+ }
1119
+
1120
+ // put the value into the query - if it has been specified in the query
1121
+ callQuery[cpKeys[cp]] = nestedValue;
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ if (callProps.body) {
1129
+ callBody = callProps.body;
1130
+ }
1131
+ if (callProps.headers) {
1132
+ callHeaders = callProps.headers;
1133
+ }
1134
+ if (callProps.handleFailure) {
1135
+ handleFail = callProps.handleFailure;
1136
+ }
1137
+ if (callProps.responseFields && callProps.responseFields.ostypePrefix) {
1138
+ ostypePrefix = callProps.responseFields.ostypePrefix;
1139
+ }
1140
+ if (callProps.responseFields && callProps.responseFields.statusValue) {
1141
+ statusValue = callProps.responseFields.statusValue;
1142
+ }
1143
+
1144
+ // !! using Generic makes it easier on the Adapter Builder (just need to change the path)
1145
+ // !! you can also replace with a specific call if that is easier
1146
+ return this.genericAdapterRequest(uriPath, uriMethod, callQuery, callBody, callHeaders, (result, error) => {
1147
+ // if we received an error or their is no response on the results return an error
1148
+ if (error) {
1149
+ if (handleFail === 'fail') {
1150
+ return callback(null, error);
1151
+ }
1152
+ return callback({}, null);
1153
+ }
1154
+ if (!result.response) {
1155
+ if (handleFail === 'fail') {
1156
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', [brokCall], null, null, null);
1157
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1158
+ return callback(null, errorObj);
1159
+ }
1160
+ return callback({}, null);
1161
+ }
1162
+
1163
+ // get the keys for the response fields
1164
+ let rfKeys = [];
1165
+ if (callProps.responseFields && Object.keys(callProps.responseFields).length > 0) {
1166
+ rfKeys = Object.keys(callProps.responseFields);
1167
+ }
1168
+
1169
+ // if we got an array returned (e.g. getDevicesFitered)
1170
+ if (Array.isArray(result.response)) {
1171
+ const listDevices = [];
1172
+ for (let a = 0; a < result.response.length; a += 1) {
1173
+ const thisDevice = result.response[a];
1174
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1175
+ if (rfKeys[rf] !== 'ostypePrefix') {
1176
+ // get the response field we are retrieving
1177
+ const loopField = callProps.responseFields[rfKeys[rf]];
1178
+ const loopArray = loopField.split('.');
1179
+ let nestedValue = thisDevice;
1180
+
1181
+ // loops through incase the field is nested
1182
+ for (let i = 0; i < loopArray.length; i += 1) {
1183
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1184
+ nestedValue = nestedValue[loopArray[i]];
1185
+ } else {
1186
+ // failed to traverse
1187
+ nestedValue = '';
1188
+ break;
1189
+ }
1190
+ }
1191
+ // if the field is ostype - need to add prefix
1192
+ if (rfKeys[rf] === 'ostype' && typeof nestedValue === 'string') {
1193
+ nestedValue = ostypePrefix + nestedValue;
1194
+ }
1195
+ // if there is a status to set, set it
1196
+ if (rfKeys[rf] === 'status') {
1197
+ // if really looking for just a good response
1198
+ if (loopField === 'return2xx' && result.icode === statusValue.toString()) {
1199
+ thisDevice.isAlive = true;
1200
+ } else if (nestedValue.toString() === statusValue.toString()) {
1201
+ thisDevice.isAlive = true;
1202
+ } else {
1203
+ thisDevice.isAlive = false;
1204
+ }
1205
+ }
1206
+ // if we found a good value
1207
+ thisDevice[rfKeys[rf]] = nestedValue;
1208
+ }
1209
+ }
1210
+
1211
+ // if there is no filter - add the device to the list
1212
+ if (!filterName || filterName.length === 0) {
1213
+ listDevices.push(thisDevice);
1214
+ } else {
1215
+ // if we have to match a filter
1216
+ let found = false;
1217
+ for (let f = 0; f < filterName.length; f += 1) {
1218
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1219
+ found = true;
1220
+ break;
1221
+ }
1222
+ }
1223
+ // matching device
1224
+ if (found) {
1225
+ listDevices.push(thisDevice);
1226
+ }
1227
+ }
1228
+ }
1229
+
1230
+ // return the array of devices
1231
+ return callback(listDevices, null);
1232
+ }
1233
+
1234
+ // if this is not an array - just about everything else, just handle as a single object
1235
+ let thisDevice = result.response;
1236
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1237
+ // skip ostypePrefix since it is not a field
1238
+ if (rfKeys[rf] !== 'ostypePrefix') {
1239
+ // get the response field we are retrieving
1240
+ const loopField = callProps.responseFields[rfKeys[rf]];
1241
+ const loopArray = loopField.split('.');
1242
+ let nestedValue = thisDevice;
1243
+
1244
+ // loops through incase the field is nested
1245
+ for (let i = 0; i < loopArray.length; i += 1) {
1246
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1247
+ nestedValue = nestedValue[loopArray[i]];
1248
+ } else {
1249
+ // failed to traverse
1250
+ nestedValue = '';
1251
+ break;
1252
+ }
1253
+ }
1254
+ // if the field is ostype - need to add prefix
1255
+ if (rfKeys[rf] === 'ostype' && typeof nestedValue === 'string') {
1256
+ nestedValue = ostypePrefix + nestedValue;
1257
+ }
1258
+ // if there is a status to set, set it
1259
+ if (rfKeys[rf] === 'status') {
1260
+ // if really looking for just a good response
1261
+ if (loopField === 'return2xx' && result.icode === statusValue.toString()) {
1262
+ thisDevice.isAlive = true;
1263
+ } else if (nestedValue.toString() === statusValue.toString()) {
1264
+ thisDevice.isAlive = true;
1265
+ } else {
1266
+ thisDevice.isAlive = false;
1267
+ }
1268
+ }
1269
+ // if we found a good value
1270
+ thisDevice[rfKeys[rf]] = nestedValue;
1271
+ }
1272
+ }
1273
+
1274
+ // if there is a filter - check the device is in the list
1275
+ if (filterName && filterName.length > 0) {
1276
+ let found = false;
1277
+ for (let f = 0; f < filterName.length; f += 1) {
1278
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1279
+ found = true;
1280
+ break;
1281
+ }
1282
+ }
1283
+ // no matching device - clear the device
1284
+ if (!found) {
1285
+ thisDevice = {};
1286
+ }
1287
+ }
1288
+
1289
+ return callback(thisDevice, null);
1290
+ });
1291
+ } catch (e) {
1292
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, e);
1293
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1294
+ return callback(null, errorObj);
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ module.exports = AdapterBase;