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