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