@itentialopensource/adapter-jira 1.7.4 → 1.7.5

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 (183) hide show
  1. package/AUTH.md +39 -0
  2. package/BROKER.md +199 -0
  3. package/CALLS.md +7365 -0
  4. package/CHANGELOG.md +8 -0
  5. package/CODE_OF_CONDUCT.md +12 -17
  6. package/CONTRIBUTING.md +88 -74
  7. package/ENHANCE.md +69 -0
  8. package/PROPERTIES.md +641 -0
  9. package/README.md +225 -502
  10. package/SUMMARY.md +9 -0
  11. package/SYSTEMINFO.md +11 -0
  12. package/TROUBLESHOOT.md +47 -0
  13. package/adapter.js +10820 -58
  14. package/adapterBase.js +1030 -248
  15. package/entities/.generic/action.json +110 -5
  16. package/entities/.generic/schema.json +6 -1
  17. package/entities/Avatars/action.json +63 -0
  18. package/entities/Avatars/schema.json +4 -1
  19. package/entities/Dashboards/action.json +80 -0
  20. package/entities/Dashboards/mockdatafiles/copyDashboard-default.json +13 -0
  21. package/entities/Dashboards/mockdatafiles/createDashboard-default.json +13 -0
  22. package/entities/Dashboards/mockdatafiles/updateDashboard-default.json +13 -0
  23. package/entities/Dashboards/schema.json +5 -1
  24. package/entities/Groups/action.json +21 -0
  25. package/entities/Groups/mockdatafiles/bulkGetGroups-default.json +16 -0
  26. package/entities/Groups/schema.json +2 -1
  27. package/entities/InstanceInformation/action.json +25 -0
  28. package/entities/InstanceInformation/mockdatafiles/getLicense-default.json +20 -0
  29. package/entities/InstanceInformation/schema.json +19 -0
  30. package/entities/IssueCustomFieldConfigurationApps/action.json +45 -0
  31. package/entities/IssueCustomFieldConfigurationApps/mockdatafiles/getCustomFieldConfiguration-default.json +34 -0
  32. package/entities/IssueCustomFieldConfigurationApps/schema.json +20 -0
  33. package/entities/IssueCustomFieldContexts/action.json +268 -0
  34. package/entities/IssueCustomFieldContexts/mockdatafiles/createCustomFieldContext-default.json +9 -0
  35. package/entities/IssueCustomFieldContexts/mockdatafiles/getContextsForField-default.json +22 -0
  36. package/entities/IssueCustomFieldContexts/mockdatafiles/getCustomFieldContextsForProjectsAndIssueTypes-default.json +23 -0
  37. package/entities/IssueCustomFieldContexts/mockdatafiles/getDefaultValues-default.json +22 -0
  38. package/entities/IssueCustomFieldContexts/mockdatafiles/getIssueTypeMappingsForContexts-default.json +20 -0
  39. package/entities/IssueCustomFieldContexts/mockdatafiles/getProjectContextMapping-default.json +16 -0
  40. package/entities/IssueCustomFieldContexts/schema.json +31 -0
  41. package/entities/IssueCustomFieldOptions/action.json +105 -0
  42. package/entities/IssueCustomFieldOptions/mockdatafiles/createCustomFieldOption-default.json +20 -0
  43. package/entities/IssueCustomFieldOptions/mockdatafiles/getOptionsForContext-default.json +26 -0
  44. package/entities/IssueCustomFieldOptions/mockdatafiles/updateCustomFieldOption-default.json +19 -0
  45. package/entities/IssueCustomFieldOptions/schema.json +23 -0
  46. package/entities/IssueCustomFieldValuesApps/action.json +44 -0
  47. package/entities/IssueCustomFieldValuesApps/schema.json +20 -0
  48. package/entities/IssueFieldConfigurations/action.json +309 -0
  49. package/entities/IssueFieldConfigurations/mockdatafiles/createFieldConfiguration-default.json +5 -0
  50. package/entities/IssueFieldConfigurations/mockdatafiles/createFieldConfigurationScheme-default.json +5 -0
  51. package/entities/IssueFieldConfigurations/mockdatafiles/getAllFieldConfigurationSchemes-default.json +23 -0
  52. package/entities/IssueFieldConfigurations/mockdatafiles/getAllFieldConfigurations-default.json +19 -0
  53. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationItems-default.json +19 -0
  54. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationSchemeMappings-default.json +33 -0
  55. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationSchemeProjectMapping-default.json +26 -0
  56. package/entities/IssueFieldConfigurations/schema.json +33 -0
  57. package/entities/IssueTypeSchemes/action.json +207 -0
  58. package/entities/IssueTypeSchemes/mockdatafiles/createIssueTypeScheme-default.json +3 -0
  59. package/entities/IssueTypeSchemes/mockdatafiles/getAllIssueTypeSchemes-default.json +26 -0
  60. package/entities/IssueTypeSchemes/mockdatafiles/getIssueTypeSchemeForProjects-default.json +44 -0
  61. package/entities/IssueTypeSchemes/mockdatafiles/getIssueTypeSchemesMapping-default.json +24 -0
  62. package/entities/IssueTypeSchemes/schema.json +28 -0
  63. package/entities/IssueTypeScreenSchemes/action.json +228 -0
  64. package/entities/IssueTypeScreenSchemes/mockdatafiles/createIssueTypeScreenScheme-default.json +3 -0
  65. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemeMappings-default.json +28 -0
  66. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemeProjectAssociations-default.json +19 -0
  67. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemes-default.json +18 -0
  68. package/entities/IssueTypeScreenSchemes/mockdatafiles/getProjectsForIssueTypeScreenScheme-default.json +27 -0
  69. package/entities/IssueTypeScreenSchemes/schema.json +29 -0
  70. package/entities/Issueattachments/action.json +42 -0
  71. package/entities/Issueattachments/schema.json +3 -1
  72. package/entities/Issuefields/action.json +122 -0
  73. package/entities/Issuefields/mockdatafiles/getContextsForFieldDeprecated-default.json +12 -0
  74. package/entities/Issuefields/mockdatafiles/getFieldsPaginated-default.json +46 -0
  75. package/entities/Issuefields/schema.json +7 -1
  76. package/entities/Issueproperties/action.json +40 -0
  77. package/entities/Issueproperties/schema.json +3 -1
  78. package/entities/Issues/action.json +45 -0
  79. package/entities/Issues/mockdatafiles/getChangeLogsByIds-default.json +65 -0
  80. package/entities/Issues/mockdatafiles/getEvents-default.json +10 -0
  81. package/entities/Issues/schema.json +20 -0
  82. package/entities/Issuesearch/action.json +20 -0
  83. package/entities/Issuesearch/mockdatafiles/matchIssues-default.json +29 -0
  84. package/entities/Issuesearch/schema.json +2 -1
  85. package/entities/Issuesecuritylevel/action.json +21 -0
  86. package/entities/Issuesecuritylevel/mockdatafiles/getIssueSecurityLevelMembers-default.json +46 -0
  87. package/entities/Issuesecuritylevel/schema.json +2 -1
  88. package/entities/Issuetypes/action.json +21 -0
  89. package/entities/Issuetypes/mockdatafiles/getIssueTypesForProject-default.json +39 -0
  90. package/entities/Issuetypes/schema.json +2 -1
  91. package/entities/Issuewatchers/action.json +20 -0
  92. package/entities/Issuewatchers/mockdatafiles/getIsWatchingIssueBulk-default.json +7 -0
  93. package/entities/Issuewatchers/schema.json +2 -1
  94. package/entities/JQL/action.json +40 -0
  95. package/entities/JQL/mockdatafiles/getAutoCompletePost-default.json +89 -0
  96. package/entities/JQL/mockdatafiles/parseJqlQueries-default.json +119 -0
  97. package/entities/JQL/schema.json +3 -1
  98. package/entities/Jiraexpressions/action.json +20 -0
  99. package/entities/Jiraexpressions/mockdatafiles/analyseExpression-default.json +47 -0
  100. package/entities/Jiraexpressions/schema.json +2 -1
  101. package/entities/Labels/action.json +25 -0
  102. package/entities/Labels/mockdatafiles/getAllLabels-default.json +10 -0
  103. package/entities/Labels/schema.json +19 -0
  104. package/entities/ProjectEmail/action.json +45 -0
  105. package/entities/ProjectEmail/mockdatafiles/getProjectEmail-default.json +6 -0
  106. package/entities/ProjectEmail/schema.json +20 -0
  107. package/entities/ProjectFeatures/action.json +45 -0
  108. package/entities/ProjectFeatures/mockdatafiles/getFeaturesForProject-default.json +24 -0
  109. package/entities/ProjectFeatures/mockdatafiles/toggleFeatureForProject-default.json +24 -0
  110. package/entities/ProjectFeatures/schema.json +20 -0
  111. package/entities/Projects/action.json +102 -0
  112. package/entities/Projects/mockdatafiles/getHierarchy-default.json +50 -0
  113. package/entities/Projects/mockdatafiles/getRecent-default.json +50 -0
  114. package/entities/Projects/mockdatafiles/restore-default.json +139 -0
  115. package/entities/Projects/schema.json +6 -1
  116. package/entities/Projecttypes/action.json +21 -0
  117. package/entities/Projecttypes/mockdatafiles/getAllAccessibleProjectTypes-default.json +16 -0
  118. package/entities/Projecttypes/schema.json +2 -1
  119. package/entities/ScreenSchemes/action.json +85 -0
  120. package/entities/ScreenSchemes/mockdatafiles/createScreenScheme-default.json +3 -0
  121. package/entities/ScreenSchemes/mockdatafiles/getScreenSchemes-default.json +28 -0
  122. package/entities/ScreenSchemes/schema.json +22 -0
  123. package/entities/Screens/action.json +81 -0
  124. package/entities/Screens/mockdatafiles/createScreen-default.json +5 -0
  125. package/entities/Screens/mockdatafiles/getScreensForField-default.json +17 -0
  126. package/entities/Screens/mockdatafiles/updateScreen-default.json +5 -0
  127. package/entities/Screens/schema.json +5 -1
  128. package/entities/Users/action.json +84 -0
  129. package/entities/Users/mockdatafiles/getAllUsers-default.json +32 -0
  130. package/entities/Users/mockdatafiles/getAllUsersDefault-default.json +32 -0
  131. package/entities/Users/mockdatafiles/getUserEmail-default.json +1 -0
  132. package/entities/Users/schema.json +5 -1
  133. package/entities/Webhooks/action.json +106 -0
  134. package/entities/Webhooks/mockdatafiles/getDynamicWebhooksForApp-default.json +40 -0
  135. package/entities/Webhooks/mockdatafiles/getFailedWebhooks-default.json +17 -0
  136. package/entities/Webhooks/mockdatafiles/refreshWebhooks-default.json +3 -0
  137. package/entities/Webhooks/mockdatafiles/registerDynamicWebhooks-default.json +15 -0
  138. package/entities/Webhooks/schema.json +23 -0
  139. package/entities/WorkflowSchemeProjectAssociations/action.json +45 -0
  140. package/entities/WorkflowSchemeProjectAssociations/mockdatafiles/getWorkflowSchemeProjectAssociations-default.json +21 -0
  141. package/entities/WorkflowSchemeProjectAssociations/schema.json +20 -0
  142. package/entities/WorkflowTransitionRules/action.json +65 -0
  143. package/entities/WorkflowTransitionRules/mockdatafiles/deleteWorkflowTransitionRuleConfigurations-default.json +34 -0
  144. package/entities/WorkflowTransitionRules/mockdatafiles/getWorkflowTransitionRuleConfigurations-default.json +56 -0
  145. package/entities/WorkflowTransitionRules/mockdatafiles/updateWorkflowTransitionRuleConfigurations-default.json +34 -0
  146. package/entities/WorkflowTransitionRules/schema.json +21 -0
  147. package/entities/Workflows/action.json +61 -0
  148. package/entities/Workflows/mockdatafiles/createWorkflow-default.json +4 -0
  149. package/entities/Workflows/mockdatafiles/getWorkflowsPaginated-default.json +140 -0
  150. package/entities/Workflows/schema.json +4 -1
  151. package/entities/Workflowschemedrafts/action.json +20 -0
  152. package/entities/Workflowschemedrafts/schema.json +2 -1
  153. package/entities/Workflowschemes/action.json +21 -0
  154. package/entities/Workflowschemes/mockdatafiles/getAllWorkflowSchemes-default.json +30 -0
  155. package/entities/Workflowschemes/schema.json +2 -1
  156. package/error.json +12 -0
  157. package/package.json +21 -13
  158. package/pronghorn.json +33339 -5948
  159. package/propertiesDecorators.json +14 -0
  160. package/propertiesSchema.json +436 -0
  161. package/refs?service=git-upload-pack +0 -0
  162. package/report/adapterInfo.json +10 -0
  163. package/report/updateReport1659707107792.json +120 -0
  164. package/sampleProperties.json +95 -3
  165. package/test/integration/adapterTestBasicGet.js +2 -2
  166. package/test/integration/adapterTestIntegration.js +3633 -106
  167. package/test/unit/adapterBaseTestUnit.js +35 -27
  168. package/test/unit/adapterTestUnit.js +4767 -115
  169. package/utils/adapterInfo.js +206 -0
  170. package/utils/addAuth.js +94 -0
  171. package/utils/basicGet.js +1 -14
  172. package/utils/entitiesToDB.js +179 -0
  173. package/utils/methodDocumentor.js +225 -0
  174. package/utils/modify.js +1 -1
  175. package/utils/packModificationScript.js +1 -1
  176. package/utils/patches2bundledDeps.js +90 -0
  177. package/utils/pre-commit.sh +5 -0
  178. package/utils/removeHooks.js +20 -0
  179. package/utils/tbScript.js +43 -22
  180. package/utils/tbUtils.js +126 -29
  181. package/utils/testRunner.js +16 -16
  182. package/utils/troubleshootingAdapter.js +2 -26
  183. package/versions.json +142 -0
package/adapterBase.js CHANGED
@@ -8,10 +8,12 @@
8
8
  /* eslint no-cond-assign: warn */
9
9
  /* eslint global-require: warn */
10
10
  /* eslint no-unused-vars: warn */
11
+ /* eslint prefer-destructuring: warn */
11
12
 
12
13
  /* Required libraries. */
13
14
  const fs = require('fs-extra');
14
15
  const path = require('path');
16
+ const jsonQuery = require('json-query');
15
17
  const EventEmitterCl = require('events').EventEmitter;
16
18
  const { execSync } = require('child_process');
17
19
 
@@ -22,6 +24,7 @@ const AjvCl = require('ajv');
22
24
  const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
23
25
  const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHandler;
24
26
 
27
+ const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
25
28
  const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
26
29
  const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
27
30
 
@@ -142,6 +145,27 @@ function updatePackage(changes) {
142
145
  return null;
143
146
  }
144
147
 
148
+ /*
149
+ * INTERNAL FUNCTION: get data from source(s) - nested
150
+ */
151
+ function getDataFromSources(loopField, sources) {
152
+ let fieldValue = loopField;
153
+
154
+ // go through the sources to find the field
155
+ for (let s = 0; s < sources.length; s += 1) {
156
+ // find the field value using jsonquery
157
+ const nestedValue = jsonQuery(loopField, { data: sources[s] }).value;
158
+
159
+ // if we found in source - set and no need to check other sources
160
+ if (nestedValue) {
161
+ fieldValue = nestedValue;
162
+ break;
163
+ }
164
+ }
165
+
166
+ return fieldValue;
167
+ }
168
+
145
169
  /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
146
170
  /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
147
171
  class AdapterBase extends EventEmitterCl {
@@ -153,6 +177,9 @@ class AdapterBase extends EventEmitterCl {
153
177
  // Instantiate the EventEmitter super class
154
178
  super();
155
179
 
180
+ // IAP home directory injected by core when running the adapter within IAP
181
+ [, , , process.env.iap_home] = process.argv;
182
+
156
183
  try {
157
184
  // Capture the adapter id
158
185
  this.id = prongid;
@@ -276,129 +303,6 @@ class AdapterBase extends EventEmitterCl {
276
303
  }
277
304
  }
278
305
 
279
- /**
280
- * updateAdapterConfiguration is used to update any of the adapter configuration files. This
281
- * allows customers to make changes to adapter configuration without having to be on the
282
- * file system.
283
- *
284
- * @function updateAdapterConfiguration
285
- * @param {string} configFile - the name of the file being updated (required)
286
- * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
287
- * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
288
- * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
289
- * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
290
- * @param {Callback} callback - The results of the call
291
- */
292
- updateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
293
- const meth = 'adapterBase-updateAdapterConfiguration';
294
- const origin = `${this.id}-${meth}`;
295
- log.trace(origin);
296
-
297
- // verify the parameters are valid
298
- if (changes === undefined || changes === null || typeof changes !== 'object'
299
- || Object.keys(changes).length === 0) {
300
- const result = {
301
- response: 'No configuration updates to make'
302
- };
303
- log.info(result.response);
304
- return callback(result, null);
305
- }
306
- if (configFile === undefined || configFile === null || configFile === '') {
307
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
308
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
309
- return callback(null, errorObj);
310
- }
311
-
312
- // take action based on configFile being changed
313
- if (configFile === 'package.json') {
314
- const pres = updatePackage(changes);
315
- if (pres) {
316
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
317
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
318
- return callback(null, errorObj);
319
- }
320
- const result = {
321
- response: 'Package updates completed - restarting adapter'
322
- };
323
- log.info(result.response);
324
- forceFail(true);
325
- return callback(result, null);
326
- }
327
- if (entity === undefined || entity === null || entity === '') {
328
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
329
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
330
- return callback(null, errorObj);
331
- }
332
-
333
- // this means we are changing an entity file so type is required
334
- if (type === undefined || type === null || type === '') {
335
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
336
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
337
- return callback(null, errorObj);
338
- }
339
-
340
- // if the entity does not exist - error
341
- const epath = `${__dirname}/entities/${entity}`;
342
- if (!fs.existsSync(epath)) {
343
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
344
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
345
- return callback(null, errorObj);
346
- }
347
-
348
- // take action based on type of file being changed
349
- if (type === 'action') {
350
- // BACKUP???
351
- const ares = updateAction(epath, action, changes);
352
- if (ares) {
353
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
354
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
355
- return callback(null, errorObj);
356
- }
357
- // AJV CHECK???
358
- // RESTORE IF NEEDED???
359
- const result = {
360
- response: `Action updates completed to entity: ${entity} - ${action}`
361
- };
362
- log.info(result.response);
363
- return callback(result, null);
364
- }
365
- if (type === 'schema') {
366
- const sres = updateSchema(epath, configFile, changes);
367
- if (sres) {
368
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
369
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
370
- return callback(null, errorObj);
371
- }
372
- const result = {
373
- response: `Schema updates completed to entity: ${entity} - ${configFile}`
374
- };
375
- log.info(result.response);
376
- return callback(result, null);
377
- }
378
- if (type === 'mock') {
379
- // if the mock directory does not exist - error
380
- const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
381
- if (!fs.existsSync(mpath)) {
382
- fs.mkdirSync(mpath);
383
- }
384
-
385
- const mres = updateMock(mpath, configFile, changes);
386
- if (mres) {
387
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
388
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
389
- return callback(null, errorObj);
390
- }
391
- const result = {
392
- response: `Mock data updates completed to entity: ${entity} - ${configFile}`
393
- };
394
- log.info(result.response);
395
- return callback(result, null);
396
- }
397
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
398
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
399
- return callback(null, errorObj);
400
- }
401
-
402
306
  /**
403
307
  * @summary Connect function is used during Pronghorn startup to provide instantiation feedback.
404
308
  *
@@ -467,7 +371,7 @@ class AdapterBase extends EventEmitterCl {
467
371
  }
468
372
 
469
373
  // call to the healthcheck in connector
470
- return this.requestHandlerInst.identifyHealthcheck(reqObj, (res, error) => {
374
+ return this.requestHandlerInst.identifyHealthcheck(myRequest, (res, error) => {
471
375
  // unhealthy
472
376
  if (error) {
473
377
  // if we were healthy, toggle health
@@ -475,9 +379,15 @@ class AdapterBase extends EventEmitterCl {
475
379
  this.emit('OFFLINE', { id: this.id });
476
380
  this.emit('DEGRADED', { id: this.id });
477
381
  this.healthy = false;
478
- log.error(`${origin}: HEALTH CHECK - Error ${error}`);
479
- } else {
382
+ if (typeof error === 'object') {
383
+ log.error(`${origin}: HEALTH CHECK - Error ${JSON.stringify(error)}`);
384
+ } else {
385
+ log.error(`${origin}: HEALTH CHECK - Error ${error}`);
386
+ }
387
+ } else if (typeof error === 'object') {
480
388
  // still log but set the level to trace
389
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${JSON.stringify(error)}`);
390
+ } else {
481
391
  log.trace(`${origin}: HEALTH CHECK - Still Errors ${error}`);
482
392
  }
483
393
 
@@ -499,68 +409,6 @@ class AdapterBase extends EventEmitterCl {
499
409
  });
500
410
  }
501
411
 
502
- /**
503
- * @summary Suspends the adapter
504
- * @param {Callback} callback - The adapater suspension status
505
- * @function suspend
506
- */
507
- suspend(mode, callback) {
508
- const origin = `${this.id}-adapterBase-suspend`;
509
- if (this.suspended) {
510
- throw new Error(`${origin}: Adapter is already suspended`);
511
- }
512
- try {
513
- this.suspended = true;
514
- this.suspendMode = mode;
515
- if (this.suspendMode === 'pause') {
516
- const props = JSON.parse(JSON.stringify(this.initProps));
517
- // To suspend adapter, enable throttling and set concurrent max to 0
518
- props.throttle.throttle_enabled = true;
519
- props.throttle.concurrent_max = 0;
520
- this.refreshProperties(props);
521
- }
522
- return callback({ suspended: true });
523
- } catch (error) {
524
- return callback(null, error);
525
- }
526
- }
527
-
528
- /**
529
- * @summary Unsuspends the adapter
530
- * @param {Callback} callback - The adapater suspension status
531
- *
532
- * @function unsuspend
533
- */
534
- unsuspend(callback) {
535
- const origin = `${this.id}-adapterBase-unsuspend`;
536
- if (!this.suspended) {
537
- throw new Error(`${origin}: Adapter is not suspended`);
538
- }
539
- if (this.suspendMode === 'pause') {
540
- const props = JSON.parse(JSON.stringify(this.initProps));
541
- // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
542
- props.throttle.throttle_enabled = true;
543
- props.throttle.concurrent_max = 1;
544
- this.refreshProperties(props);
545
- setTimeout(() => {
546
- this.getQueue((q, error) => {
547
- // console.log("Items in queue: " + String(q.length))
548
- if (q.length === 0) {
549
- // if queue is empty, return to initial properties state
550
- this.refreshProperties(this.initProps);
551
- this.suspended = false;
552
- return callback({ suspended: false });
553
- }
554
- // recursive call to check queue again every second
555
- return this.unsuspend(callback);
556
- });
557
- }, 1000);
558
- } else {
559
- this.suspended = false;
560
- callback({ suspend: false });
561
- }
562
- }
563
-
564
412
  /**
565
413
  * getAllFunctions is used to get all of the exposed function in the adapter
566
414
  *
@@ -586,12 +434,67 @@ class AdapterBase extends EventEmitterCl {
586
434
  }
587
435
 
588
436
  /**
589
- * getWorkflowFunctions is used to get all of the workflow function in the adapter
437
+ * checkActionFiles is used to update the validation of the action files.
438
+ *
439
+ * @function checkActionFiles
440
+ */
441
+ checkActionFiles() {
442
+ const origin = `${this.id}-adapterBase-checkActionFiles`;
443
+ log.trace(origin);
444
+
445
+ // validate the action files for the adapter
446
+ try {
447
+ return this.requestHandlerInst.checkActionFiles();
448
+ } catch (e) {
449
+ return ['Exception increase log level'];
450
+ }
451
+ }
452
+
453
+ /**
454
+ * checkProperties is used to validate the adapter properties.
455
+ *
456
+ * @function checkProperties
457
+ * @param {Object} properties - an object containing all of the properties
458
+ */
459
+ checkProperties(properties) {
460
+ const origin = `${this.myid}-adapterBase-checkProperties`;
461
+ log.trace(origin);
462
+
463
+ // validate the properties for the adapter
464
+ try {
465
+ return this.requestHandlerInst.checkProperties(properties);
466
+ } catch (e) {
467
+ return { exception: 'Exception increase log level' };
468
+ }
469
+ }
470
+
471
+ /**
472
+ * @summary Takes in property text and an encoding/encryption and returns the resulting
473
+ * encoded/encrypted string
474
+ *
475
+ * @function encryptProperty
476
+ * @param {String} property - the property to encrypt
477
+ * @param {String} technique - the technique to use to encrypt
478
+ *
479
+ * @param {Callback} callback - a callback function to return the result
480
+ * Encrypted String or the Error
481
+ */
482
+ encryptProperty(property, technique, callback) {
483
+ const origin = `${this.id}-adapterBase-encryptProperty`;
484
+ log.trace(origin);
485
+
486
+ // Make the call -
487
+ // encryptProperty(property, technique, callback)
488
+ return this.requestHandlerInst.encryptProperty(property, technique, callback);
489
+ }
490
+
491
+ /**
492
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
590
493
  * @param {array} ignoreThese - additional methods to ignore (optional)
591
494
  *
592
- * @function getWorkflowFunctions
495
+ * @function iapGetAdapterWorkflowFunctions
593
496
  */
594
- getWorkflowFunctions(ignoreThese) {
497
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
595
498
  const myfunctions = this.getAllFunctions();
596
499
  const wffunctions = [];
597
500
 
@@ -601,9 +504,7 @@ class AdapterBase extends EventEmitterCl {
601
504
  // got to the second tier (adapterBase)
602
505
  break;
603
506
  }
604
- if (myfunctions[m] !== 'hasEntity' && myfunctions[m] !== 'verifyCapability' && myfunctions[m] !== 'updateEntityCache'
605
- && myfunctions[m] !== 'healthCheck' && myfunctions[m] !== 'getWorkflowFunctions'
606
- && !(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
507
+ if (!(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
607
508
  let found = false;
608
509
  if (ignoreThese && Array.isArray(ignoreThese)) {
609
510
  for (let i = 0; i < ignoreThese.length; i += 1) {
@@ -622,30 +523,136 @@ class AdapterBase extends EventEmitterCl {
622
523
  }
623
524
 
624
525
  /**
625
- * checkActionFiles is used to update the validation of the action files.
526
+ * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This
527
+ * allows customers to make changes to adapter configuration without having to be on the
528
+ * file system.
626
529
  *
627
- * @function checkActionFiles
530
+ * @function iapUpdateAdapterConfiguration
531
+ * @param {string} configFile - the name of the file being updated (required)
532
+ * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
533
+ * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
534
+ * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
535
+ * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
536
+ * @param {Callback} callback - The results of the call
628
537
  */
629
- checkActionFiles() {
630
- const origin = `${this.id}-adapterBase-checkActionFiles`;
538
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
539
+ const meth = 'adapterBase-iapUpdateAdapterConfiguration';
540
+ const origin = `${this.id}-${meth}`;
631
541
  log.trace(origin);
632
542
 
633
- // validate the action files for the adapter
634
- try {
635
- return this.requestHandlerInst.checkActionFiles();
636
- } catch (e) {
637
- return ['Exception increase log level'];
543
+ // verify the parameters are valid
544
+ if (changes === undefined || changes === null || typeof changes !== 'object'
545
+ || Object.keys(changes).length === 0) {
546
+ const result = {
547
+ response: 'No configuration updates to make'
548
+ };
549
+ log.info(result.response);
550
+ return callback(result, null);
551
+ }
552
+ if (configFile === undefined || configFile === null || configFile === '') {
553
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
554
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
555
+ return callback(null, errorObj);
556
+ }
557
+
558
+ // take action based on configFile being changed
559
+ if (configFile === 'package.json') {
560
+ const pres = updatePackage(changes);
561
+ if (pres) {
562
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
563
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
564
+ return callback(null, errorObj);
565
+ }
566
+ const result = {
567
+ response: 'Package updates completed - restarting adapter'
568
+ };
569
+ log.info(result.response);
570
+ forceFail(true);
571
+ return callback(result, null);
572
+ }
573
+ if (entity === undefined || entity === null || entity === '') {
574
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
575
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
576
+ return callback(null, errorObj);
577
+ }
578
+
579
+ // this means we are changing an entity file so type is required
580
+ if (type === undefined || type === null || type === '') {
581
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
582
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
583
+ return callback(null, errorObj);
584
+ }
585
+
586
+ // if the entity does not exist - error
587
+ const epath = `${__dirname}/entities/${entity}`;
588
+ if (!fs.existsSync(epath)) {
589
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
590
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
591
+ return callback(null, errorObj);
592
+ }
593
+
594
+ // take action based on type of file being changed
595
+ if (type === 'action') {
596
+ // BACKUP???
597
+ const ares = updateAction(epath, action, changes);
598
+ if (ares) {
599
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
600
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
601
+ return callback(null, errorObj);
602
+ }
603
+ // AJV CHECK???
604
+ // RESTORE IF NEEDED???
605
+ const result = {
606
+ response: `Action updates completed to entity: ${entity} - ${action}`
607
+ };
608
+ log.info(result.response);
609
+ return callback(result, null);
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
+ const result = {
619
+ response: `Schema updates completed to entity: ${entity} - ${configFile}`
620
+ };
621
+ log.info(result.response);
622
+ return callback(result, null);
638
623
  }
624
+ if (type === 'mock') {
625
+ // if the mock directory does not exist - error
626
+ const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
627
+ if (!fs.existsSync(mpath)) {
628
+ fs.mkdirSync(mpath);
629
+ }
630
+
631
+ const mres = updateMock(mpath, configFile, changes);
632
+ if (mres) {
633
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
634
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
635
+ return callback(null, errorObj);
636
+ }
637
+ const result = {
638
+ response: `Mock data updates completed to entity: ${entity} - ${configFile}`
639
+ };
640
+ log.info(result.response);
641
+ return callback(result, null);
642
+ }
643
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
644
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
645
+ return callback(null, errorObj);
639
646
  }
640
647
 
641
648
  /**
642
649
  * See if the API path provided is found in this adapter
643
650
  *
644
- * @function findPath
651
+ * @function iapFindAdapterPath
645
652
  * @param {string} apiPath - the api path to check on
646
653
  * @param {Callback} callback - The results of the call
647
654
  */
648
- findPath(apiPath, callback) {
655
+ iapFindAdapterPath(apiPath, callback) {
649
656
  const result = {
650
657
  apiPath
651
658
  };
@@ -687,7 +694,7 @@ class AdapterBase extends EventEmitterCl {
687
694
  log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
688
695
  const fitem = {
689
696
  entity: entities[e],
690
- action: actions[a].name,
697
+ action: actions.actions[a].name,
691
698
  method: actions.actions[a].method,
692
699
  path: actions.actions[a].entitypath
693
700
  };
@@ -722,66 +729,90 @@ class AdapterBase extends EventEmitterCl {
722
729
  }
723
730
 
724
731
  /**
725
- * checkProperties is used to validate the adapter properties.
726
- *
727
- * @function checkProperties
728
- * @param {Object} properties - an object containing all of the properties
732
+ * @summary Suspends the adapter
733
+ * @param {Callback} callback - The adapater suspension status
734
+ * @function iapSuspendAdapter
729
735
  */
730
- checkProperties(properties) {
731
- const origin = `${this.myid}-adapterBase-checkProperties`;
732
- log.trace(origin);
733
-
734
- // validate the properties for the adapter
736
+ iapSuspendAdapter(mode, callback) {
737
+ const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
738
+ if (this.suspended) {
739
+ throw new Error(`${origin}: Adapter is already suspended`);
740
+ }
735
741
  try {
736
- return this.requestHandlerInst.checkProperties(properties);
737
- } catch (e) {
738
- return { exception: 'Exception increase log level' };
742
+ this.suspended = true;
743
+ this.suspendMode = mode;
744
+ if (this.suspendMode === 'pause') {
745
+ const props = JSON.parse(JSON.stringify(this.initProps));
746
+ // To suspend adapter, enable throttling and set concurrent max to 0
747
+ props.throttle.throttle_enabled = true;
748
+ props.throttle.concurrent_max = 0;
749
+ this.refreshProperties(props);
750
+ }
751
+ return callback({ suspended: true });
752
+ } catch (error) {
753
+ return callback(null, error);
739
754
  }
740
755
  }
741
756
 
742
757
  /**
743
- * getQueue is used to get information for all of the requests currently in the queue.
758
+ * @summary Unsuspends the adapter
759
+ * @param {Callback} callback - The adapater suspension status
744
760
  *
745
- * @function getQueue
746
- * @param {Callback} callback - a callback function to return the result (Queue) or the error
761
+ * @function iapUnsuspendAdapter
747
762
  */
748
- getQueue(callback) {
749
- const origin = `${this.id}-adapterBase-getQueue`;
750
- log.trace(origin);
751
-
752
- return this.requestHandlerInst.getQueue(callback);
763
+ iapUnsuspendAdapter(callback) {
764
+ const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
765
+ if (!this.suspended) {
766
+ throw new Error(`${origin}: Adapter is not suspended`);
767
+ }
768
+ if (this.suspendMode === 'pause') {
769
+ const props = JSON.parse(JSON.stringify(this.initProps));
770
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
771
+ props.throttle.throttle_enabled = true;
772
+ props.throttle.concurrent_max = 1;
773
+ this.refreshProperties(props);
774
+ setTimeout(() => {
775
+ this.getQueue((q, error) => {
776
+ // console.log("Items in queue: " + String(q.length))
777
+ if (q.length === 0) {
778
+ // if queue is empty, return to initial properties state
779
+ this.refreshProperties(this.initProps);
780
+ this.suspended = false;
781
+ return callback({ suspended: false });
782
+ }
783
+ // recursive call to check queue again every second
784
+ return this.iapUnsuspendAdapter(callback);
785
+ });
786
+ }, 1000);
787
+ } else {
788
+ this.suspended = false;
789
+ callback({ suspend: false });
790
+ }
753
791
  }
754
792
 
755
793
  /**
756
- * @summary Takes in property text and an encoding/encryption and returns the resulting
757
- * encoded/encrypted string
794
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
758
795
  *
759
- * @function encryptProperty
760
- * @param {String} property - the property to encrypt
761
- * @param {String} technique - the technique to use to encrypt
762
- *
763
- * @param {Callback} callback - a callback function to return the result
764
- * Encrypted String or the Error
796
+ * @function iapGetAdapterQueue
797
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
765
798
  */
766
- encryptProperty(property, technique, callback) {
767
- const origin = `${this.id}-adapterBase-encryptProperty`;
799
+ iapGetAdapterQueue(callback) {
800
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
768
801
  log.trace(origin);
769
802
 
770
- // Make the call -
771
- // encryptProperty(property, technique, callback)
772
- return this.requestHandlerInst.encryptProperty(property, technique, callback);
803
+ return this.requestHandlerInst.getQueue(callback);
773
804
  }
774
805
 
775
806
  /**
776
807
  * @summary runs troubleshoot scripts for adapter
777
808
  *
778
- * @function troubleshoot
809
+ * @function iapTroubleshootAdapter
779
810
  * @param {Object} props - the connection, healthcheck and authentication properties
780
811
  * @param {boolean} persistFlag - whether the adapter properties should be updated
781
812
  * @param {Adapter} adapter - adapter instance to troubleshoot
782
813
  * @param {Callback} callback - callback function to return troubleshoot results
783
814
  */
784
- async troubleshoot(props, persistFlag, adapter, callback) {
815
+ async iapTroubleshootAdapter(props, persistFlag, adapter, callback) {
785
816
  try {
786
817
  const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
787
818
  if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
@@ -796,11 +827,11 @@ class AdapterBase extends EventEmitterCl {
796
827
  /**
797
828
  * @summary runs healthcheck script for adapter
798
829
  *
799
- * @function runHealthcheck
830
+ * @function iapRunAdapterHealthcheck
800
831
  * @param {Adapter} adapter - adapter instance to troubleshoot
801
832
  * @param {Callback} callback - callback function to return healthcheck status
802
833
  */
803
- async runHealthcheck(adapter, callback) {
834
+ async iapRunAdapterHealthcheck(adapter, callback) {
804
835
  try {
805
836
  const result = await tbUtils.healthCheck(adapter);
806
837
  if (result) {
@@ -815,13 +846,13 @@ class AdapterBase extends EventEmitterCl {
815
846
  /**
816
847
  * @summary runs connectivity check script for adapter
817
848
  *
818
- * @function runConnectivity
849
+ * @function iapRunAdapterConnectivity
819
850
  * @param {Adapter} adapter - adapter instance to troubleshoot
820
851
  * @param {Callback} callback - callback function to return connectivity status
821
852
  */
822
- async runConnectivity(callback) {
853
+ async iapRunAdapterConnectivity(callback) {
823
854
  try {
824
- const { serviceItem } = await troubleshootingAdapter.getAdapterConfig();
855
+ const { serviceItem } = await tbUtils.getAdapterConfig();
825
856
  const { host } = serviceItem.properties.properties;
826
857
  const result = tbUtils.runConnectivity(host, false);
827
858
  if (result.failCount > 0) {
@@ -836,10 +867,10 @@ class AdapterBase extends EventEmitterCl {
836
867
  /**
837
868
  * @summary runs basicGet script for adapter
838
869
  *
839
- * @function runBasicGet
870
+ * @function iapRunAdapterBasicGet
840
871
  * @param {Callback} callback - callback function to return basicGet result
841
872
  */
842
- runBasicGet(callback) {
873
+ iapRunAdapterBasicGet(callback) {
843
874
  try {
844
875
  const result = tbUtils.runBasicGet(false);
845
876
  if (result.failCount > 0) {
@@ -851,6 +882,28 @@ class AdapterBase extends EventEmitterCl {
851
882
  }
852
883
  }
853
884
 
885
+ /**
886
+ * @summary moves entities to mongo database
887
+ *
888
+ * @function iapMoveAdapterEntitiesToDB
889
+ *
890
+ * @return {Callback} - containing the response from the mongo transaction
891
+ */
892
+ async iapMoveAdapterEntitiesToDB(callback) {
893
+ const meth = 'adapterBase-iapMoveAdapterEntitiesToDB';
894
+ const origin = `${this.id}-${meth}`;
895
+ log.trace(origin);
896
+
897
+ try {
898
+ const result = await entitiesToDB.moveEntitiesToDB(__dirname, { pronghornProps: this.allProps, id: this.id });
899
+ return callback(result, null);
900
+ } catch (err) {
901
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, err);
902
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
903
+ return callback(null, err.message);
904
+ }
905
+ }
906
+
854
907
  /**
855
908
  * @summary take the entities and add them to the cache
856
909
  *
@@ -1001,6 +1054,735 @@ class AdapterBase extends EventEmitterCl {
1001
1054
  return [];
1002
1055
  }
1003
1056
  }
1057
+
1058
+ /**
1059
+ * @summary Determines if this adapter supports any in a list of entities
1060
+ *
1061
+ * @function hasEntities
1062
+ * @param {String} entityType - the entity type to check for
1063
+ * @param {Array} entityList - the list of entities we are looking for
1064
+ *
1065
+ * @param {Callback} callback - A map where the entity is the key and the
1066
+ * value is true or false
1067
+ */
1068
+ hasEntities(entityType, entityList, callback) {
1069
+ const origin = `${this.id}-adapter-hasEntities`;
1070
+ log.trace(origin);
1071
+
1072
+ switch (entityType) {
1073
+ case 'Device':
1074
+ return this.hasDevices(entityList, callback);
1075
+ default:
1076
+ return callback(null, `${this.id} does not support entity ${entityType}`);
1077
+ }
1078
+ }
1079
+
1080
+ /**
1081
+ * @summary Helper method for hasEntities for the specific device case
1082
+ *
1083
+ * @param {Array} deviceList - array of unique device identifiers
1084
+ * @param {Callback} callback - A map where the device is the key and the
1085
+ * value is true or false
1086
+ */
1087
+ hasDevices(deviceList, callback) {
1088
+ const origin = `${this.id}-adapter-hasDevices`;
1089
+ log.trace(origin);
1090
+
1091
+ const findings = deviceList.reduce((map, device) => {
1092
+ // eslint-disable-next-line no-param-reassign
1093
+ map[device] = false;
1094
+ log.debug(`In reduce: ${JSON.stringify(map)}`);
1095
+ return map;
1096
+ }, {});
1097
+ const apiCalls = deviceList.map((device) => new Promise((resolve) => {
1098
+ this.getDevice(device, (result, error) => {
1099
+ if (error) {
1100
+ log.debug(`In map error: ${JSON.stringify(device)}`);
1101
+ return resolve({ name: device, found: false });
1102
+ }
1103
+ log.debug(`In map: ${JSON.stringify(device)}`);
1104
+ return resolve({ name: device, found: true });
1105
+ });
1106
+ }));
1107
+ Promise.all(apiCalls).then((results) => {
1108
+ results.forEach((device) => {
1109
+ findings[device.name] = device.found;
1110
+ });
1111
+ log.debug(`FINDINGS: ${JSON.stringify(findings)}`);
1112
+ return callback(findings);
1113
+ }).catch((errors) => {
1114
+ log.error('Unable to do device lookup.');
1115
+ return callback(null, { code: 503, message: 'Unable to do device lookup.', error: errors });
1116
+ });
1117
+ }
1118
+
1119
+ /**
1120
+ * @summary Make one of the needed Broker calls - could be one of many
1121
+ *
1122
+ * @function iapMakeBrokerCall
1123
+ * @param {string} brokCall - the name of the broker call (required)
1124
+ * @param {object} callProps - the proeprties for the broker call (required)
1125
+ * @param {object} devResp - the device details to extract needed inputs (required)
1126
+ * @param {string} filterName - any filter to search on (required)
1127
+ *
1128
+ * @param {getCallback} callback - a callback function to return the result of the call
1129
+ */
1130
+ iapMakeBrokerCall(brokCall, callProps, devResp, filterName, callback) {
1131
+ const meth = 'adapterBase-iapMakeBrokerCall';
1132
+ const origin = `${this.id}-${meth}`;
1133
+ log.trace(origin);
1134
+
1135
+ try {
1136
+ let uriPath = '';
1137
+ let uriMethod = 'GET';
1138
+ let callQuery = {};
1139
+ let callBody = {};
1140
+ let callHeaders = {};
1141
+ let handleFail = 'fail';
1142
+ let ostypePrefix = '';
1143
+ let statusValue = 'true';
1144
+ if (callProps.path) {
1145
+ uriPath = `${callProps.path}`;
1146
+
1147
+ // make any necessary changes to the path
1148
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1149
+ const rqKeys = Object.keys(callProps.requestFields);
1150
+
1151
+ // get the field from the provided device
1152
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1153
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1154
+
1155
+ // put the value into the path - if it has been specified in the path
1156
+ uriPath = uriPath.replace(`{${rqKeys[rq]}}`, fieldValue);
1157
+ }
1158
+ }
1159
+ }
1160
+ if (callProps.method) {
1161
+ uriMethod = callProps.method;
1162
+ }
1163
+ if (callProps.query) {
1164
+ callQuery = callProps.query;
1165
+
1166
+ // go through the query params to check for variable values
1167
+ const cpKeys = Object.keys(callQuery);
1168
+ for (let cp = 0; cp < cpKeys.length; cp += 1) {
1169
+ if (callQuery[cpKeys[cp]].startsWith('{') && callQuery[cpKeys[cp]].endsWith('}')) {
1170
+ // make any necessary changes to the query params
1171
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1172
+ const rqKeys = Object.keys(callProps.requestFields);
1173
+
1174
+ // get the field from the provided device
1175
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1176
+ if (cpKeys[cp] === rqKeys[rq]) {
1177
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1178
+
1179
+ // put the value into the query - if it has been specified in the query
1180
+ callQuery[cpKeys[cp]] = fieldValue;
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ if (callProps.body) {
1188
+ callBody = callProps.body;
1189
+
1190
+ // go through the body fields to check for variable values
1191
+ const cbKeys = Object.keys(callBody);
1192
+ for (let cb = 0; cb < cbKeys.length; cb += 1) {
1193
+ if (callBody[cbKeys[cb]].startsWith('{') && callBody[cbKeys[cb]].endsWith('}')) {
1194
+ // make any necessary changes to the query params
1195
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1196
+ const rqKeys = Object.keys(callProps.requestFields);
1197
+
1198
+ // get the field from the provided device
1199
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1200
+ if (cbKeys[cb] === rqKeys[rq]) {
1201
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1202
+
1203
+ // put the value into the query - if it has been specified in the query
1204
+ callBody[cbKeys[cb]] = fieldValue;
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1211
+ if (callProps.headers) {
1212
+ callHeaders = callProps.headers;
1213
+
1214
+ // go through the body fields to check for variable values
1215
+ const chKeys = Object.keys(callHeaders);
1216
+ for (let ch = 0; ch < chKeys.length; ch += 1) {
1217
+ if (callHeaders[chKeys[ch]].startsWith('{') && callHeaders[chKeys[ch]].endsWith('}')) {
1218
+ // make any necessary changes to the query params
1219
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1220
+ const rqKeys = Object.keys(callProps.requestFields);
1221
+
1222
+ // get the field from the provided device
1223
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1224
+ if (chKeys[ch] === rqKeys[rq]) {
1225
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1226
+
1227
+ // put the value into the query - if it has been specified in the query
1228
+ callHeaders[chKeys[ch]] = fieldValue;
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+ }
1234
+ }
1235
+ if (callProps.handleFailure) {
1236
+ handleFail = callProps.handleFailure;
1237
+ }
1238
+ if (callProps.responseFields && callProps.responseFields.ostypePrefix) {
1239
+ ostypePrefix = callProps.responseFields.ostypePrefix;
1240
+ }
1241
+ if (callProps.responseFields && callProps.responseFields.statusValue) {
1242
+ statusValue = callProps.responseFields.statusValue;
1243
+ }
1244
+
1245
+ // !! using Generic makes it easier on the Adapter Builder (just need to change the path)
1246
+ // !! you can also replace with a specific call if that is easier
1247
+ return this.genericAdapterRequest(uriPath, uriMethod, callQuery, callBody, callHeaders, (result, error) => {
1248
+ // if we received an error or their is no response on the results return an error
1249
+ if (error) {
1250
+ if (handleFail === 'fail') {
1251
+ return callback(null, error);
1252
+ }
1253
+ return callback({}, null);
1254
+ }
1255
+ if (!result.response) {
1256
+ if (handleFail === 'fail') {
1257
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', [brokCall], null, null, null);
1258
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1259
+ return callback(null, errorObj);
1260
+ }
1261
+ return callback({}, null);
1262
+ }
1263
+
1264
+ // get the response piece we care about from the response
1265
+ const myResult = result;
1266
+ if (callProps.responseDatakey) {
1267
+ myResult.response = jsonQuery(callProps.responseDatakey, { data: myResult.response }).value;
1268
+ }
1269
+
1270
+ // get the keys for the response fields
1271
+ let rfKeys = [];
1272
+ if (callProps.responseFields && Object.keys(callProps.responseFields).length > 0) {
1273
+ rfKeys = Object.keys(callProps.responseFields);
1274
+ }
1275
+
1276
+ // if we got an array returned (e.g. getDevicesFitered)
1277
+ if (Array.isArray(myResult.response)) {
1278
+ const listDevices = [];
1279
+ for (let a = 0; a < myResult.response.length; a += 1) {
1280
+ const thisDevice = myResult.response[a];
1281
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1282
+ if (rfKeys[rf] !== 'ostypePrefix') {
1283
+ let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1284
+
1285
+ // if the field is ostype - need to add prefix
1286
+ if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1287
+ fieldValue = ostypePrefix + fieldValue;
1288
+ }
1289
+ // if there is a status to set, set it
1290
+ if (rfKeys[rf] === 'status') {
1291
+ // if really looking for just a good response
1292
+ if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1293
+ thisDevice.isAlive = true;
1294
+ } else if (fieldValue.toString() === statusValue.toString()) {
1295
+ thisDevice.isAlive = true;
1296
+ } else {
1297
+ thisDevice.isAlive = false;
1298
+ }
1299
+ }
1300
+ // if we found a good value
1301
+ thisDevice[rfKeys[rf]] = fieldValue;
1302
+ }
1303
+ }
1304
+
1305
+ // if there is no filter - add the device to the list
1306
+ if (!filterName || filterName.length === 0) {
1307
+ listDevices.push(thisDevice);
1308
+ } else {
1309
+ // if we have to match a filter
1310
+ let found = false;
1311
+ for (let f = 0; f < filterName.length; f += 1) {
1312
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1313
+ found = true;
1314
+ break;
1315
+ }
1316
+ }
1317
+ // matching device
1318
+ if (found) {
1319
+ listDevices.push(thisDevice);
1320
+ }
1321
+ }
1322
+ }
1323
+
1324
+ // return the array of devices
1325
+ return callback(listDevices, null);
1326
+ }
1327
+
1328
+ // if this is not an array - just about everything else, just handle as a single object
1329
+ let thisDevice = myResult.response;
1330
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1331
+ // skip ostypePrefix since it is not a field
1332
+ if (rfKeys[rf] !== 'ostypePrefix') {
1333
+ let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1334
+
1335
+ // if the field is ostype - need to add prefix
1336
+ if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1337
+ fieldValue = ostypePrefix + fieldValue;
1338
+ }
1339
+ // if there is a status to set, set it
1340
+ if (rfKeys[rf] === 'status') {
1341
+ // if really looking for just a good response
1342
+ if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1343
+ thisDevice.isAlive = true;
1344
+ } else if (fieldValue.toString() === statusValue.toString()) {
1345
+ thisDevice.isAlive = true;
1346
+ } else {
1347
+ thisDevice.isAlive = false;
1348
+ }
1349
+ }
1350
+ // if we found a good value
1351
+ thisDevice[rfKeys[rf]] = fieldValue;
1352
+ }
1353
+ }
1354
+
1355
+ // if there is a filter - check the device is in the list
1356
+ if (filterName && filterName.length > 0) {
1357
+ let found = false;
1358
+ for (let f = 0; f < filterName.length; f += 1) {
1359
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1360
+ found = true;
1361
+ break;
1362
+ }
1363
+ }
1364
+ // no matching device - clear the device
1365
+ if (!found) {
1366
+ thisDevice = {};
1367
+ }
1368
+ }
1369
+
1370
+ return callback(thisDevice, null);
1371
+ });
1372
+ } catch (e) {
1373
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, e);
1374
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1375
+ return callback(null, errorObj);
1376
+ }
1377
+ }
1378
+
1379
+ /**
1380
+ * @summary Get Appliance that match the deviceName
1381
+ *
1382
+ * @function getDevice
1383
+ * @param {String} deviceName - the deviceName to find (required)
1384
+ *
1385
+ * @param {getCallback} callback - a callback function to return the result
1386
+ * (appliance) or the error
1387
+ */
1388
+ getDevice(deviceName, callback) {
1389
+ const meth = 'adapterBase-getDevice';
1390
+ const origin = `${this.id}-${meth}`;
1391
+ log.trace(origin);
1392
+
1393
+ // make sure we are set up for device broker getDevice
1394
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevice || this.allProps.devicebroker.getDevice.length === 0 || !this.allProps.devicebroker.getDevice[0].path) {
1395
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevice.path'], null, null, null);
1396
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1397
+ return callback(null, errorObj);
1398
+ }
1399
+
1400
+ /* HERE IS WHERE YOU VALIDATE DATA */
1401
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1402
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1403
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1404
+ return callback(null, errorObj);
1405
+ }
1406
+
1407
+ try {
1408
+ // need to get the device so we can convert the deviceName to an id
1409
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1410
+ const opts = {
1411
+ filter: {
1412
+ name: deviceName
1413
+ }
1414
+ };
1415
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1416
+ // if we received an error or their is no response on the results return an error
1417
+ if (ferr) {
1418
+ return callback(null, ferr);
1419
+ }
1420
+ if (devs.list.length < 1) {
1421
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1422
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1423
+ return callback(null, errorObj);
1424
+ }
1425
+
1426
+ const callPromises = [];
1427
+ for (let i = 0; i < this.allProps.devicebroker.getDevice.length; i += 1) {
1428
+ // Perform component calls here.
1429
+ callPromises.push(
1430
+ new Promise((resolve, reject) => {
1431
+ this.iapMakeBrokerCall('getDevice', this.allProps.devicebroker.getDevice[i], [devs.list[0]], null, (callRet, callErr) => {
1432
+ // return an error
1433
+ if (callErr) {
1434
+ reject(callErr);
1435
+ } else {
1436
+ // return the data
1437
+ resolve(callRet);
1438
+ }
1439
+ });
1440
+ })
1441
+ );
1442
+ }
1443
+
1444
+ // return an array of repsonses
1445
+ return Promise.all(callPromises).then((results) => {
1446
+ let myResult = {};
1447
+ results.forEach((result) => {
1448
+ myResult = { ...myResult, ...result };
1449
+ });
1450
+
1451
+ return callback(myResult, null);
1452
+ });
1453
+ });
1454
+ } catch (ex) {
1455
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1456
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1457
+ return callback(null, errorObj);
1458
+ }
1459
+ }
1460
+
1461
+ /**
1462
+ * @summary Get Appliances that match the filter
1463
+ *
1464
+ * @function getDevicesFiltered
1465
+ * @param {Object} options - the data to use to filter the appliances (optional)
1466
+ *
1467
+ * @param {getCallback} callback - a callback function to return the result
1468
+ * (appliances) or the error
1469
+ */
1470
+ getDevicesFiltered(options, callback) {
1471
+ const meth = 'adapterBase-getDevicesFiltered';
1472
+ const origin = `${this.id}-${meth}`;
1473
+ log.trace(origin);
1474
+
1475
+ // make sure we are set up for device broker getDevicesFiltered
1476
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevicesFiltered || this.allProps.devicebroker.getDevicesFiltered.length === 0 || !this.allProps.devicebroker.getDevicesFiltered[0].path) {
1477
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevicesFiltered.path'], null, null, null);
1478
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1479
+ return callback(null, errorObj);
1480
+ }
1481
+
1482
+ // verify the required fields have been provided
1483
+ if (options === undefined || options === null || options === '' || options.length === 0) {
1484
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['options'], null, null, null);
1485
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1486
+ return callback(null, errorObj);
1487
+ }
1488
+ log.debug(`Device Filter Options: ${JSON.stringify(options)}`);
1489
+
1490
+ try {
1491
+ // TODO - get pagination working
1492
+ // const nextToken = options.start;
1493
+ // const maxResults = options.limit;
1494
+
1495
+ // set up the filter of Device Names
1496
+ let filterName = [];
1497
+ if (options && options.filter && options.filter.name) {
1498
+ // when this hack is removed, remove the lint ignore above
1499
+ if (Array.isArray(options.filter.name)) {
1500
+ // eslint-disable-next-line prefer-destructuring
1501
+ filterName = options.filter.name;
1502
+ } else {
1503
+ filterName = [options.filter.name];
1504
+ }
1505
+ }
1506
+
1507
+ // TODO - get sort and order working
1508
+ /*
1509
+ if (options && options.sort) {
1510
+ reqObj.uriOptions.sort = JSON.stringify(options.sort);
1511
+ }
1512
+ if (options && options.order) {
1513
+ reqObj.uriOptions.order = options.order;
1514
+ }
1515
+ */
1516
+ const callPromises = [];
1517
+ for (let i = 0; i < this.allProps.devicebroker.getDevicesFiltered.length; i += 1) {
1518
+ // Perform component calls here.
1519
+ callPromises.push(
1520
+ new Promise((resolve, reject) => {
1521
+ this.iapMakeBrokerCall('getDevicesFiltered', this.allProps.devicebroker.getDevicesFiltered[i], [{ fake: 'fakedata' }], filterName, (callRet, callErr) => {
1522
+ // return an error
1523
+ if (callErr) {
1524
+ reject(callErr);
1525
+ } else {
1526
+ // return the data
1527
+ resolve(callRet);
1528
+ }
1529
+ });
1530
+ })
1531
+ );
1532
+ }
1533
+
1534
+ // return an array of repsonses
1535
+ return Promise.all(callPromises).then((results) => {
1536
+ let myResult = [];
1537
+ results.forEach((result) => {
1538
+ if (Array.isArray(result)) {
1539
+ myResult = [...myResult, ...result];
1540
+ } else if (Object.keys(result).length > 0) {
1541
+ myResult.push(result);
1542
+ }
1543
+ });
1544
+
1545
+ log.debug(`${origin}: Found #${myResult.length} devices.`);
1546
+ log.debug(`Devices: ${JSON.stringify(myResult)}`);
1547
+ return callback({ total: myResult.length, list: myResult });
1548
+ });
1549
+ } catch (ex) {
1550
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1551
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1552
+ return callback(null, errorObj);
1553
+ }
1554
+ }
1555
+
1556
+ /**
1557
+ * @summary Gets the status for the provided appliance
1558
+ *
1559
+ * @function isAlive
1560
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1561
+ *
1562
+ * @param {configCallback} callback - callback function to return the result
1563
+ * (appliance isAlive) or the error
1564
+ */
1565
+ isAlive(deviceName, callback) {
1566
+ const meth = 'adapterBase-isAlive';
1567
+ const origin = `${this.id}-${meth}`;
1568
+ log.trace(origin);
1569
+
1570
+ // make sure we are set up for device broker isAlive
1571
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.isAlive || this.allProps.devicebroker.isAlive.length === 0 || !this.allProps.devicebroker.isAlive[0].path) {
1572
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.isAlive.path'], null, null, null);
1573
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1574
+ return callback(null, errorObj);
1575
+ }
1576
+
1577
+ // verify the required fields have been provided
1578
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1579
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1580
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1581
+ return callback(null, errorObj);
1582
+ }
1583
+
1584
+ try {
1585
+ // need to get the device so we can convert the deviceName to an id
1586
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1587
+ const opts = {
1588
+ filter: {
1589
+ name: deviceName
1590
+ }
1591
+ };
1592
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1593
+ // if we received an error or their is no response on the results return an error
1594
+ if (ferr) {
1595
+ return callback(null, ferr);
1596
+ }
1597
+ if (devs.list.length < 1) {
1598
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1599
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1600
+ return callback(null, errorObj);
1601
+ }
1602
+
1603
+ const callPromises = [];
1604
+ for (let i = 0; i < this.allProps.devicebroker.isAlive.length; i += 1) {
1605
+ // Perform component calls here.
1606
+ callPromises.push(
1607
+ new Promise((resolve, reject) => {
1608
+ this.iapMakeBrokerCall('isAlive', this.allProps.devicebroker.isAlive[i], [devs.list[0]], null, (callRet, callErr) => {
1609
+ // return an error
1610
+ if (callErr) {
1611
+ reject(callErr);
1612
+ } else {
1613
+ // return the data
1614
+ resolve(callRet);
1615
+ }
1616
+ });
1617
+ })
1618
+ );
1619
+ }
1620
+
1621
+ // return an array of repsonses
1622
+ return Promise.all(callPromises).then((results) => {
1623
+ let myResult = {};
1624
+ results.forEach((result) => {
1625
+ myResult = { ...myResult, ...result };
1626
+ });
1627
+
1628
+ let response = true;
1629
+ if (myResult.isAlive !== null && myResult.isAlive !== undefined && myResult.isAlive === false) {
1630
+ response = false;
1631
+ }
1632
+ return callback(response);
1633
+ });
1634
+ });
1635
+ } catch (ex) {
1636
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1637
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1638
+ return callback(null, errorObj);
1639
+ }
1640
+ }
1641
+
1642
+ /**
1643
+ * @summary Gets a config for the provided Appliance
1644
+ *
1645
+ * @function getConfig
1646
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1647
+ * @param {String} format - the desired format of the config. (optional)
1648
+ *
1649
+ * @param {configCallback} callback - callback function to return the result
1650
+ * (appliance config) or the error
1651
+ */
1652
+ getConfig(deviceName, format, callback) {
1653
+ const meth = 'adapterBase-getConfig';
1654
+ const origin = `${this.id}-${meth}`;
1655
+ log.trace(origin);
1656
+
1657
+ // make sure we are set up for device broker getConfig
1658
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getConfig || this.allProps.devicebroker.getConfig.length === 0 || !this.allProps.devicebroker.getConfig[0].path) {
1659
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getConfig.path'], null, null, null);
1660
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1661
+ return callback(null, errorObj);
1662
+ }
1663
+
1664
+ // verify the required fields have been provided
1665
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1666
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1667
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1668
+ return callback(null, errorObj);
1669
+ }
1670
+
1671
+ try {
1672
+ // need to get the device so we can convert the deviceName to an id
1673
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1674
+ const opts = {
1675
+ filter: {
1676
+ name: deviceName
1677
+ }
1678
+ };
1679
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1680
+ // if we received an error or their is no response on the results return an error
1681
+ if (ferr) {
1682
+ return callback(null, ferr);
1683
+ }
1684
+ if (devs.list.length < 1) {
1685
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1686
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1687
+ return callback(null, errorObj);
1688
+ }
1689
+
1690
+ const callPromises = [];
1691
+ for (let i = 0; i < this.allProps.devicebroker.getConfig.length; i += 1) {
1692
+ // Perform component calls here.
1693
+ callPromises.push(
1694
+ new Promise((resolve, reject) => {
1695
+ this.iapMakeBrokerCall('getConfig', this.allProps.devicebroker.getConfig[i], [devs.list[0]], null, (callRet, callErr) => {
1696
+ // return an error
1697
+ if (callErr) {
1698
+ reject(callErr);
1699
+ } else {
1700
+ // return the data
1701
+ resolve(callRet);
1702
+ }
1703
+ });
1704
+ })
1705
+ );
1706
+ }
1707
+
1708
+ // return an array of repsonses
1709
+ return Promise.all(callPromises).then((results) => {
1710
+ let myResult = {};
1711
+ results.forEach((result) => {
1712
+ myResult = { ...myResult, ...result };
1713
+ });
1714
+
1715
+ // return the result
1716
+ const newResponse = {
1717
+ response: JSON.stringify(myResult, null, 2)
1718
+ };
1719
+ return callback(newResponse, null);
1720
+ });
1721
+ });
1722
+ } catch (ex) {
1723
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1724
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1725
+ return callback(null, errorObj);
1726
+ }
1727
+ }
1728
+
1729
+ /**
1730
+ * @summary Gets the device count from the system
1731
+ *
1732
+ * @function iapGetDeviceCount
1733
+ *
1734
+ * @param {getCallback} callback - callback function to return the result
1735
+ * (count) or the error
1736
+ */
1737
+ iapGetDeviceCount(callback) {
1738
+ const meth = 'adapterBase-iapGetDeviceCount';
1739
+ const origin = `${this.id}-${meth}`;
1740
+ log.trace(origin);
1741
+
1742
+ // make sure we are set up for device broker getCount
1743
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getCount || this.allProps.devicebroker.getCount.length === 0 || !this.allProps.devicebroker.getCount[0].path) {
1744
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getCount.path'], null, null, null);
1745
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1746
+ return callback(null, errorObj);
1747
+ }
1748
+
1749
+ // verify the required fields have been provided
1750
+
1751
+ try {
1752
+ const callPromises = [];
1753
+ for (let i = 0; i < this.allProps.devicebroker.getCount.length; i += 1) {
1754
+ // Perform component calls here.
1755
+ callPromises.push(
1756
+ new Promise((resolve, reject) => {
1757
+ this.iapMakeBrokerCall('getCount', this.allProps.devicebroker.getCount[i], null, null, (callRet, callErr) => {
1758
+ // return an error
1759
+ if (callErr) {
1760
+ reject(callErr);
1761
+ } else {
1762
+ // return the data
1763
+ resolve(callRet);
1764
+ }
1765
+ });
1766
+ })
1767
+ );
1768
+ }
1769
+
1770
+ // return an array of repsonses
1771
+ return Promise.all(callPromises).then((results) => {
1772
+ let myResult = {};
1773
+ results.forEach((result) => {
1774
+ myResult = { ...myResult, ...result };
1775
+ });
1776
+
1777
+ // return the result
1778
+ return callback({ count: myResult.length });
1779
+ });
1780
+ } catch (ex) {
1781
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1782
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1783
+ return callback(null, errorObj);
1784
+ }
1785
+ }
1004
1786
  }
1005
1787
 
1006
1788
  module.exports = AdapterBase;