@itentialopensource/adapter-jira 1.7.2 → 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 (189) hide show
  1. package/.eslintignore +1 -0
  2. package/AUTH.md +39 -0
  3. package/BROKER.md +199 -0
  4. package/CALLS.md +7365 -0
  5. package/CHANGELOG.md +24 -0
  6. package/CODE_OF_CONDUCT.md +12 -17
  7. package/CONTRIBUTING.md +88 -74
  8. package/ENHANCE.md +69 -0
  9. package/PROPERTIES.md +641 -0
  10. package/README.md +228 -420
  11. package/SUMMARY.md +9 -0
  12. package/SYSTEMINFO.md +11 -0
  13. package/TROUBLESHOOT.md +47 -0
  14. package/adapter.js +18753 -4899
  15. package/adapterBase.js +1274 -236
  16. package/entities/.generic/action.json +214 -0
  17. package/entities/.generic/schema.json +28 -0
  18. package/entities/Avatars/action.json +63 -0
  19. package/entities/Avatars/schema.json +4 -1
  20. package/entities/Dashboards/action.json +80 -0
  21. package/entities/Dashboards/mockdatafiles/copyDashboard-default.json +13 -0
  22. package/entities/Dashboards/mockdatafiles/createDashboard-default.json +13 -0
  23. package/entities/Dashboards/mockdatafiles/updateDashboard-default.json +13 -0
  24. package/entities/Dashboards/schema.json +5 -1
  25. package/entities/Groups/action.json +21 -0
  26. package/entities/Groups/mockdatafiles/bulkGetGroups-default.json +16 -0
  27. package/entities/Groups/schema.json +2 -1
  28. package/entities/InstanceInformation/action.json +25 -0
  29. package/entities/InstanceInformation/mockdatafiles/getLicense-default.json +20 -0
  30. package/entities/InstanceInformation/schema.json +19 -0
  31. package/entities/IssueCustomFieldConfigurationApps/action.json +45 -0
  32. package/entities/IssueCustomFieldConfigurationApps/mockdatafiles/getCustomFieldConfiguration-default.json +34 -0
  33. package/entities/IssueCustomFieldConfigurationApps/schema.json +20 -0
  34. package/entities/IssueCustomFieldContexts/action.json +268 -0
  35. package/entities/IssueCustomFieldContexts/mockdatafiles/createCustomFieldContext-default.json +9 -0
  36. package/entities/IssueCustomFieldContexts/mockdatafiles/getContextsForField-default.json +22 -0
  37. package/entities/IssueCustomFieldContexts/mockdatafiles/getCustomFieldContextsForProjectsAndIssueTypes-default.json +23 -0
  38. package/entities/IssueCustomFieldContexts/mockdatafiles/getDefaultValues-default.json +22 -0
  39. package/entities/IssueCustomFieldContexts/mockdatafiles/getIssueTypeMappingsForContexts-default.json +20 -0
  40. package/entities/IssueCustomFieldContexts/mockdatafiles/getProjectContextMapping-default.json +16 -0
  41. package/entities/IssueCustomFieldContexts/schema.json +31 -0
  42. package/entities/IssueCustomFieldOptions/action.json +105 -0
  43. package/entities/IssueCustomFieldOptions/mockdatafiles/createCustomFieldOption-default.json +20 -0
  44. package/entities/IssueCustomFieldOptions/mockdatafiles/getOptionsForContext-default.json +26 -0
  45. package/entities/IssueCustomFieldOptions/mockdatafiles/updateCustomFieldOption-default.json +19 -0
  46. package/entities/IssueCustomFieldOptions/schema.json +23 -0
  47. package/entities/IssueCustomFieldValuesApps/action.json +44 -0
  48. package/entities/IssueCustomFieldValuesApps/schema.json +20 -0
  49. package/entities/IssueFieldConfigurations/action.json +309 -0
  50. package/entities/IssueFieldConfigurations/mockdatafiles/createFieldConfiguration-default.json +5 -0
  51. package/entities/IssueFieldConfigurations/mockdatafiles/createFieldConfigurationScheme-default.json +5 -0
  52. package/entities/IssueFieldConfigurations/mockdatafiles/getAllFieldConfigurationSchemes-default.json +23 -0
  53. package/entities/IssueFieldConfigurations/mockdatafiles/getAllFieldConfigurations-default.json +19 -0
  54. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationItems-default.json +19 -0
  55. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationSchemeMappings-default.json +33 -0
  56. package/entities/IssueFieldConfigurations/mockdatafiles/getFieldConfigurationSchemeProjectMapping-default.json +26 -0
  57. package/entities/IssueFieldConfigurations/schema.json +33 -0
  58. package/entities/IssueTypeSchemes/action.json +207 -0
  59. package/entities/IssueTypeSchemes/mockdatafiles/createIssueTypeScheme-default.json +3 -0
  60. package/entities/IssueTypeSchemes/mockdatafiles/getAllIssueTypeSchemes-default.json +26 -0
  61. package/entities/IssueTypeSchemes/mockdatafiles/getIssueTypeSchemeForProjects-default.json +44 -0
  62. package/entities/IssueTypeSchemes/mockdatafiles/getIssueTypeSchemesMapping-default.json +24 -0
  63. package/entities/IssueTypeSchemes/schema.json +28 -0
  64. package/entities/IssueTypeScreenSchemes/action.json +228 -0
  65. package/entities/IssueTypeScreenSchemes/mockdatafiles/createIssueTypeScreenScheme-default.json +3 -0
  66. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemeMappings-default.json +28 -0
  67. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemeProjectAssociations-default.json +19 -0
  68. package/entities/IssueTypeScreenSchemes/mockdatafiles/getIssueTypeScreenSchemes-default.json +18 -0
  69. package/entities/IssueTypeScreenSchemes/mockdatafiles/getProjectsForIssueTypeScreenScheme-default.json +27 -0
  70. package/entities/IssueTypeScreenSchemes/schema.json +29 -0
  71. package/entities/Issueattachments/action.json +42 -0
  72. package/entities/Issueattachments/schema.json +3 -1
  73. package/entities/Issuefields/action.json +122 -0
  74. package/entities/Issuefields/mockdatafiles/getContextsForFieldDeprecated-default.json +12 -0
  75. package/entities/Issuefields/mockdatafiles/getFieldsPaginated-default.json +46 -0
  76. package/entities/Issuefields/schema.json +7 -1
  77. package/entities/Issueproperties/action.json +40 -0
  78. package/entities/Issueproperties/schema.json +3 -1
  79. package/entities/Issues/action.json +45 -0
  80. package/entities/Issues/mockdatafiles/getChangeLogsByIds-default.json +65 -0
  81. package/entities/Issues/mockdatafiles/getEvents-default.json +10 -0
  82. package/entities/Issues/schema.json +20 -0
  83. package/entities/Issuesearch/action.json +20 -0
  84. package/entities/Issuesearch/mockdatafiles/matchIssues-default.json +29 -0
  85. package/entities/Issuesearch/schema.json +2 -1
  86. package/entities/Issuesecuritylevel/action.json +21 -0
  87. package/entities/Issuesecuritylevel/mockdatafiles/getIssueSecurityLevelMembers-default.json +46 -0
  88. package/entities/Issuesecuritylevel/schema.json +2 -1
  89. package/entities/Issuetypes/action.json +21 -0
  90. package/entities/Issuetypes/mockdatafiles/getIssueTypesForProject-default.json +39 -0
  91. package/entities/Issuetypes/schema.json +2 -1
  92. package/entities/Issuewatchers/action.json +20 -0
  93. package/entities/Issuewatchers/mockdatafiles/getIsWatchingIssueBulk-default.json +7 -0
  94. package/entities/Issuewatchers/schema.json +2 -1
  95. package/entities/JQL/action.json +40 -0
  96. package/entities/JQL/mockdatafiles/getAutoCompletePost-default.json +89 -0
  97. package/entities/JQL/mockdatafiles/parseJqlQueries-default.json +119 -0
  98. package/entities/JQL/schema.json +3 -1
  99. package/entities/Jiraexpressions/action.json +20 -0
  100. package/entities/Jiraexpressions/mockdatafiles/analyseExpression-default.json +47 -0
  101. package/entities/Jiraexpressions/schema.json +2 -1
  102. package/entities/Labels/action.json +25 -0
  103. package/entities/Labels/mockdatafiles/getAllLabels-default.json +10 -0
  104. package/entities/Labels/schema.json +19 -0
  105. package/entities/ProjectEmail/action.json +45 -0
  106. package/entities/ProjectEmail/mockdatafiles/getProjectEmail-default.json +6 -0
  107. package/entities/ProjectEmail/schema.json +20 -0
  108. package/entities/ProjectFeatures/action.json +45 -0
  109. package/entities/ProjectFeatures/mockdatafiles/getFeaturesForProject-default.json +24 -0
  110. package/entities/ProjectFeatures/mockdatafiles/toggleFeatureForProject-default.json +24 -0
  111. package/entities/ProjectFeatures/schema.json +20 -0
  112. package/entities/Projects/action.json +102 -0
  113. package/entities/Projects/mockdatafiles/getHierarchy-default.json +50 -0
  114. package/entities/Projects/mockdatafiles/getRecent-default.json +50 -0
  115. package/entities/Projects/mockdatafiles/restore-default.json +139 -0
  116. package/entities/Projects/schema.json +6 -1
  117. package/entities/Projecttypes/action.json +21 -0
  118. package/entities/Projecttypes/mockdatafiles/getAllAccessibleProjectTypes-default.json +16 -0
  119. package/entities/Projecttypes/schema.json +2 -1
  120. package/entities/ScreenSchemes/action.json +85 -0
  121. package/entities/ScreenSchemes/mockdatafiles/createScreenScheme-default.json +3 -0
  122. package/entities/ScreenSchemes/mockdatafiles/getScreenSchemes-default.json +28 -0
  123. package/entities/ScreenSchemes/schema.json +22 -0
  124. package/entities/Screens/action.json +81 -0
  125. package/entities/Screens/mockdatafiles/createScreen-default.json +5 -0
  126. package/entities/Screens/mockdatafiles/getScreensForField-default.json +17 -0
  127. package/entities/Screens/mockdatafiles/updateScreen-default.json +5 -0
  128. package/entities/Screens/schema.json +5 -1
  129. package/entities/Users/action.json +84 -0
  130. package/entities/Users/mockdatafiles/getAllUsers-default.json +32 -0
  131. package/entities/Users/mockdatafiles/getAllUsersDefault-default.json +32 -0
  132. package/entities/Users/mockdatafiles/getUserEmail-default.json +1 -0
  133. package/entities/Users/schema.json +5 -1
  134. package/entities/Webhooks/action.json +106 -0
  135. package/entities/Webhooks/mockdatafiles/getDynamicWebhooksForApp-default.json +40 -0
  136. package/entities/Webhooks/mockdatafiles/getFailedWebhooks-default.json +17 -0
  137. package/entities/Webhooks/mockdatafiles/refreshWebhooks-default.json +3 -0
  138. package/entities/Webhooks/mockdatafiles/registerDynamicWebhooks-default.json +15 -0
  139. package/entities/Webhooks/schema.json +23 -0
  140. package/entities/WorkflowSchemeProjectAssociations/action.json +45 -0
  141. package/entities/WorkflowSchemeProjectAssociations/mockdatafiles/getWorkflowSchemeProjectAssociations-default.json +21 -0
  142. package/entities/WorkflowSchemeProjectAssociations/schema.json +20 -0
  143. package/entities/WorkflowTransitionRules/action.json +65 -0
  144. package/entities/WorkflowTransitionRules/mockdatafiles/deleteWorkflowTransitionRuleConfigurations-default.json +34 -0
  145. package/entities/WorkflowTransitionRules/mockdatafiles/getWorkflowTransitionRuleConfigurations-default.json +56 -0
  146. package/entities/WorkflowTransitionRules/mockdatafiles/updateWorkflowTransitionRuleConfigurations-default.json +34 -0
  147. package/entities/WorkflowTransitionRules/schema.json +21 -0
  148. package/entities/Workflows/action.json +61 -0
  149. package/entities/Workflows/mockdatafiles/createWorkflow-default.json +4 -0
  150. package/entities/Workflows/mockdatafiles/getWorkflowsPaginated-default.json +140 -0
  151. package/entities/Workflows/schema.json +4 -1
  152. package/entities/Workflowschemedrafts/action.json +20 -0
  153. package/entities/Workflowschemedrafts/schema.json +2 -1
  154. package/entities/Workflowschemes/action.json +21 -0
  155. package/entities/Workflowschemes/mockdatafiles/getAllWorkflowSchemes-default.json +30 -0
  156. package/entities/Workflowschemes/schema.json +2 -1
  157. package/error.json +12 -0
  158. package/package.json +42 -18
  159. package/pronghorn.json +27769 -74
  160. package/propertiesDecorators.json +14 -0
  161. package/propertiesSchema.json +472 -4
  162. package/refs?service=git-upload-pack +0 -0
  163. package/report/adapterInfo.json +10 -0
  164. package/report/updateReport1615159462702.json +95 -0
  165. package/report/updateReport1659707107792.json +120 -0
  166. package/sampleProperties.json +103 -6
  167. package/test/integration/adapterTestBasicGet.js +85 -0
  168. package/test/integration/adapterTestConnectivity.js +93 -0
  169. package/test/integration/adapterTestIntegration.js +3633 -101
  170. package/test/unit/adapterBaseTestUnit.js +949 -0
  171. package/test/unit/adapterTestUnit.js +4766 -109
  172. package/utils/adapterInfo.js +206 -0
  173. package/utils/addAuth.js +94 -0
  174. package/utils/basicGet.js +50 -0
  175. package/utils/checkMigrate.js +63 -0
  176. package/utils/entitiesToDB.js +179 -0
  177. package/utils/findPath.js +74 -0
  178. package/utils/methodDocumentor.js +225 -0
  179. package/utils/modify.js +154 -0
  180. package/utils/packModificationScript.js +1 -1
  181. package/utils/patches2bundledDeps.js +90 -0
  182. package/utils/pre-commit.sh +5 -0
  183. package/utils/removeHooks.js +20 -0
  184. package/utils/tbScript.js +184 -0
  185. package/utils/tbUtils.js +469 -0
  186. package/utils/testRunner.js +16 -16
  187. package/utils/troubleshootingAdapter.js +190 -0
  188. package/versions.json +142 -0
  189. package/img/adapter.png +0 -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,10 @@ 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'));
28
+ const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
29
+ const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
30
+
25
31
  let propUtil = null;
26
32
 
27
33
  /*
@@ -139,6 +145,27 @@ function updatePackage(changes) {
139
145
  return null;
140
146
  }
141
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
+
142
169
  /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
143
170
  /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
144
171
  class AdapterBase extends EventEmitterCl {
@@ -150,14 +177,19 @@ class AdapterBase extends EventEmitterCl {
150
177
  // Instantiate the EventEmitter super class
151
178
  super();
152
179
 
180
+ // IAP home directory injected by core when running the adapter within IAP
181
+ [, , , process.env.iap_home] = process.argv;
182
+
153
183
  try {
154
184
  // Capture the adapter id
155
185
  this.id = prongid;
156
186
  this.propUtilInst = new PropUtilCl(prongid, __dirname);
157
187
  propUtil = this.propUtilInst;
158
-
188
+ this.initProps = properties;
159
189
  this.alive = false;
160
190
  this.healthy = false;
191
+ this.suspended = false;
192
+ this.suspendMode = 'pause';
161
193
  this.caching = false;
162
194
  this.repeatCacheCount = 0;
163
195
  this.allowFailover = 'AD.300';
@@ -242,6 +274,7 @@ class AdapterBase extends EventEmitterCl {
242
274
  // properties that this code cares about
243
275
  this.healthcheckType = this.allProps.healthcheck.type;
244
276
  this.healthcheckInterval = this.allProps.healthcheck.frequency;
277
+ this.healthcheckQuery = this.allProps.healthcheck.query_object;
245
278
 
246
279
  // set the failover codes from properties
247
280
  if (this.allProps.request.failover_codes) {
@@ -270,129 +303,6 @@ class AdapterBase extends EventEmitterCl {
270
303
  }
271
304
  }
272
305
 
273
- /**
274
- * updateAdapterConfiguration is used to update any of the adapter configuration files. This
275
- * allows customers to make changes to adapter configuration without having to be on the
276
- * file system.
277
- *
278
- * @function updateAdapterConfiguration
279
- * @param {string} configFile - the name of the file being updated (required)
280
- * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
281
- * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
282
- * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
283
- * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
284
- * @param {Callback} callback - The results of the call
285
- */
286
- updateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
287
- const meth = 'adapterBase-updateAdapterConfiguration';
288
- const origin = `${this.id}-${meth}`;
289
- log.trace(origin);
290
-
291
- // verify the parameters are valid
292
- if (changes === undefined || changes === null || typeof changes !== 'object'
293
- || Object.keys(changes).length === 0) {
294
- const result = {
295
- response: 'No configuration updates to make'
296
- };
297
- log.info(result.response);
298
- return callback(result, null);
299
- }
300
- if (configFile === undefined || configFile === null || configFile === '') {
301
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
302
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
303
- return callback(null, errorObj);
304
- }
305
-
306
- // take action based on configFile being changed
307
- if (configFile === 'package.json') {
308
- const pres = updatePackage(changes);
309
- if (pres) {
310
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
311
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
312
- return callback(null, errorObj);
313
- }
314
- const result = {
315
- response: 'Package updates completed - restarting adapter'
316
- };
317
- log.info(result.response);
318
- forceFail(true);
319
- return callback(result, null);
320
- }
321
- if (entity === undefined || entity === null || entity === '') {
322
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
323
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
324
- return callback(null, errorObj);
325
- }
326
-
327
- // this means we are changing an entity file so type is required
328
- if (type === undefined || type === null || type === '') {
329
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
330
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
331
- return callback(null, errorObj);
332
- }
333
-
334
- // if the entity does not exist - error
335
- const epath = `${__dirname}/entities/${entity}`;
336
- if (!fs.existsSync(epath)) {
337
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
338
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
339
- return callback(null, errorObj);
340
- }
341
-
342
- // take action based on type of file being changed
343
- if (type === 'action') {
344
- // BACKUP???
345
- const ares = updateAction(epath, action, changes);
346
- if (ares) {
347
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
348
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
349
- return callback(null, errorObj);
350
- }
351
- // AJV CHECK???
352
- // RESTORE IF NEEDED???
353
- const result = {
354
- response: `Action updates completed to entity: ${entity} - ${action}`
355
- };
356
- log.info(result.response);
357
- return callback(result, null);
358
- }
359
- if (type === 'schema') {
360
- const sres = updateSchema(epath, configFile, changes);
361
- if (sres) {
362
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
363
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
364
- return callback(null, errorObj);
365
- }
366
- const result = {
367
- response: `Schema updates completed to entity: ${entity} - ${configFile}`
368
- };
369
- log.info(result.response);
370
- return callback(result, null);
371
- }
372
- if (type === 'mock') {
373
- // if the mock directory does not exist - error
374
- const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
375
- if (!fs.existsSync(mpath)) {
376
- fs.mkdirSync(mpath);
377
- }
378
-
379
- const mres = updateMock(mpath, configFile, changes);
380
- if (mres) {
381
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
382
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
383
- return callback(null, errorObj);
384
- }
385
- const result = {
386
- response: `Mock data updates completed to entity: ${entity} - ${configFile}`
387
- };
388
- log.info(result.response);
389
- return callback(result, null);
390
- }
391
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
392
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
393
- return callback(null, errorObj);
394
- }
395
-
396
306
  /**
397
307
  * @summary Connect function is used during Pronghorn startup to provide instantiation feedback.
398
308
  *
@@ -446,8 +356,22 @@ class AdapterBase extends EventEmitterCl {
446
356
  const origin = `${this.id}-adapterBase-healthCheck`;
447
357
  log.trace(origin);
448
358
 
359
+ // if there is healthcheck query_object property, it needs to be added to the adapter
360
+ let myRequest = reqObj;
361
+ if (this.healthcheckQuery && Object.keys(this.healthcheckQuery).length > 0) {
362
+ if (myRequest && myRequest.uriQuery) {
363
+ myRequest.uriQuery = { ...myRequest.uriQuery, ...this.healthcheckQuery };
364
+ } else if (myRequest) {
365
+ myRequest.uriQuery = this.healthcheckQuery;
366
+ } else {
367
+ myRequest = {
368
+ uriQuery: this.healthcheckQuery
369
+ };
370
+ }
371
+ }
372
+
449
373
  // call to the healthcheck in connector
450
- return this.requestHandlerInst.identifyHealthcheck(reqObj, (res, error) => {
374
+ return this.requestHandlerInst.identifyHealthcheck(myRequest, (res, error) => {
451
375
  // unhealthy
452
376
  if (error) {
453
377
  // if we were healthy, toggle health
@@ -455,9 +379,15 @@ class AdapterBase extends EventEmitterCl {
455
379
  this.emit('OFFLINE', { id: this.id });
456
380
  this.emit('DEGRADED', { id: this.id });
457
381
  this.healthy = false;
458
- log.error(`${origin}: HEALTH CHECK - Error ${error}`);
459
- } 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') {
460
388
  // still log but set the level to trace
389
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${JSON.stringify(error)}`);
390
+ } else {
461
391
  log.trace(`${origin}: HEALTH CHECK - Still Errors ${error}`);
462
392
  }
463
393
 
@@ -503,30 +433,6 @@ class AdapterBase extends EventEmitterCl {
503
433
  return myfunctions;
504
434
  }
505
435
 
506
- /**
507
- * getWorkflowFunctions is used to get all of the workflow function in the adapter
508
- *
509
- * @function getAllFunctions
510
- */
511
- getWorkflowFunctions() {
512
- const myfunctions = this.getAllFunctions();
513
- const wffunctions = [];
514
-
515
- // remove the functions that should not be in a Workflow
516
- for (let m = 0; m < myfunctions.length; m += 1) {
517
- if (myfunctions[m] === 'addEntityCache') {
518
- // got to the second tier (adapterBase)
519
- break;
520
- }
521
- if (myfunctions[m] !== 'hasEntity' && myfunctions[m] !== 'verifyCapability' && myfunctions[m] !== 'updateEntityCache'
522
- && myfunctions[m] !== 'healthCheck' && !(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
523
- wffunctions.push(myfunctions[m]);
524
- }
525
- }
526
-
527
- return wffunctions;
528
- }
529
-
530
436
  /**
531
437
  * checkActionFiles is used to update the validation of the action files.
532
438
  *
@@ -562,19 +468,6 @@ class AdapterBase extends EventEmitterCl {
562
468
  }
563
469
  }
564
470
 
565
- /**
566
- * getQueue is used to get information for all of the requests currently in the queue.
567
- *
568
- * @function getQueue
569
- * @param {Callback} callback - a callback function to return the result (Queue) or the error
570
- */
571
- getQueue(callback) {
572
- const origin = `${this.id}-adapterBase-getQueue`;
573
- log.trace(origin);
574
-
575
- return this.requestHandlerInst.getQueue(callback);
576
- }
577
-
578
471
  /**
579
472
  * @summary Takes in property text and an encoding/encryption and returns the resulting
580
473
  * encoded/encrypted string
@@ -596,93 +489,509 @@ class AdapterBase extends EventEmitterCl {
596
489
  }
597
490
 
598
491
  /**
599
- * @summary take the entities and add them to the cache
600
- *
601
- * @function addEntityCache
602
- * @param {String} entityType - the type of the entities
603
- * @param {Array} data - the list of entities
604
- * @param {String} key - unique key for the entities
492
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
493
+ * @param {array} ignoreThese - additional methods to ignore (optional)
605
494
  *
606
- * @param {Callback} callback - An array of whether the adapter can has the
607
- * desired capability or an error
495
+ * @function iapGetAdapterWorkflowFunctions
608
496
  */
609
- addEntityCache(entityType, entities, key, callback) {
610
- const meth = 'adapterBase-addEntityCache';
611
- const origin = `${this.id}-${meth}`;
612
- log.trace(origin);
613
-
614
- // list containing the items to add to the cache
615
- const entityIds = [];
616
-
617
- if (entities && Object.hasOwnProperty.call(entities, 'response')
618
- && Array.isArray(entities.response)) {
619
- for (let e = 0; e < entities.response.length; e += 1) {
620
- entityIds.push(entities.response[e][key]);
621
- }
622
- }
497
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
498
+ const myfunctions = this.getAllFunctions();
499
+ const wffunctions = [];
623
500
 
624
- // add the entities to the cache
625
- return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
626
- if (error) {
627
- return callback(null, error);
628
- }
629
- if (!loaded) {
630
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
631
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
632
- return callback(null, errorObj);
501
+ // remove the functions that should not be in a Workflow
502
+ for (let m = 0; m < myfunctions.length; m += 1) {
503
+ if (myfunctions[m] === 'addEntityCache') {
504
+ // got to the second tier (adapterBase)
505
+ break;
633
506
  }
634
-
635
- return callback(loaded);
636
- });
637
- }
638
-
639
- /**
640
- * @summary sees if the entity is in the entity list or not
641
- *
642
- * @function entityInList
643
- * @param {String/Array} entityId - the specific entity we are looking for
644
- * @param {Array} data - the list of entities
645
- *
646
- * @param {Callback} callback - An array of whether the adapter can has the
647
- * desired capability or an error
648
- */
649
- entityInList(entityId, data) {
650
- const origin = `${this.id}-adapterBase-entityInList`;
651
- log.trace(origin);
652
-
653
- // need to check on the entities that were passed in
654
- if (Array.isArray(entityId)) {
655
- const resEntity = [];
656
-
657
- for (let e = 0; e < entityId.length; e += 1) {
658
- if (data.includes(entityId)) {
659
- resEntity.push(true);
660
- } else {
661
- resEntity.push(false);
507
+ if (!(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
508
+ let found = false;
509
+ if (ignoreThese && Array.isArray(ignoreThese)) {
510
+ for (let i = 0; i < ignoreThese.length; i += 1) {
511
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
512
+ found = true;
513
+ }
514
+ }
515
+ }
516
+ if (!found) {
517
+ wffunctions.push(myfunctions[m]);
662
518
  }
663
519
  }
664
-
665
- return resEntity;
666
520
  }
667
521
 
668
- // does the entity list include the specific entity
669
- return [data.includes(entityId)];
522
+ return wffunctions;
670
523
  }
671
524
 
672
525
  /**
673
- * @summary prepare results for verify capability so they are true/false
674
- *
675
- * @function capabilityResults
676
- * @param {Array} results - the results from the capability check
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.
677
529
  *
678
- * @param {Callback} callback - An array of whether the adapter can has the
679
- * desired capability or an error
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
680
537
  */
681
- capabilityResults(results, callback) {
682
- const meth = 'adapterBase-getQueue';
538
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
539
+ const meth = 'adapterBase-iapUpdateAdapterConfiguration';
683
540
  const origin = `${this.id}-${meth}`;
684
541
  log.trace(origin);
685
- let locResults = results;
542
+
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);
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);
646
+ }
647
+
648
+ /**
649
+ * See if the API path provided is found in this adapter
650
+ *
651
+ * @function iapFindAdapterPath
652
+ * @param {string} apiPath - the api path to check on
653
+ * @param {Callback} callback - The results of the call
654
+ */
655
+ iapFindAdapterPath(apiPath, callback) {
656
+ const result = {
657
+ apiPath
658
+ };
659
+
660
+ // verify the path was provided
661
+ if (!apiPath) {
662
+ log.error('NO API PATH PROVIDED!');
663
+ result.found = false;
664
+ result.message = 'NO PATH PROVIDED!';
665
+ return callback(null, result);
666
+ }
667
+
668
+ // make sure the entities directory exists
669
+ const entitydir = path.join(__dirname, 'entities');
670
+ if (!fs.statSync(entitydir).isDirectory()) {
671
+ log.error('Could not find the entities directory');
672
+ result.found = false;
673
+ result.message = 'Could not find the entities directory';
674
+ return callback(null, result);
675
+ }
676
+
677
+ const entities = fs.readdirSync(entitydir);
678
+ const fitems = [];
679
+
680
+ // need to go through each entity in the entities directory
681
+ for (let e = 0; e < entities.length; e += 1) {
682
+ // make sure the entity is a directory - do not care about extra files
683
+ // only entities (dir)
684
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
685
+ // see if the action file exists in the entity
686
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
687
+ // Read the entity actions from the file system
688
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
689
+
690
+ // go through all of the actions set the appropriate info in the newActions
691
+ for (let a = 0; a < actions.actions.length; a += 1) {
692
+ if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
693
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
694
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
695
+ const fitem = {
696
+ entity: entities[e],
697
+ action: actions.actions[a].name,
698
+ method: actions.actions[a].method,
699
+ path: actions.actions[a].entitypath
700
+ };
701
+ fitems.push(fitem);
702
+ }
703
+ }
704
+ } else {
705
+ log.error(`Could not find entities ${entities[e]} action.json file`);
706
+ result.found = false;
707
+ result.message = `Could not find entities ${entities[e]} action.json file`;
708
+ return callback(null, result);
709
+ }
710
+ } else {
711
+ log.error(`Could not find entities ${entities[e]} directory`);
712
+ result.found = false;
713
+ result.message = `Could not find entities ${entities[e]} directory`;
714
+ return callback(null, result);
715
+ }
716
+ }
717
+
718
+ if (fitems.length === 0) {
719
+ log.info('PATH NOT FOUND!');
720
+ result.found = false;
721
+ result.message = 'API PATH NOT FOUND!';
722
+ return callback(null, result);
723
+ }
724
+
725
+ result.foundIn = fitems;
726
+ result.found = true;
727
+ result.message = 'API PATH FOUND!';
728
+ return callback(result, null);
729
+ }
730
+
731
+ /**
732
+ * @summary Suspends the adapter
733
+ * @param {Callback} callback - The adapater suspension status
734
+ * @function iapSuspendAdapter
735
+ */
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
+ }
741
+ try {
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);
754
+ }
755
+ }
756
+
757
+ /**
758
+ * @summary Unsuspends the adapter
759
+ * @param {Callback} callback - The adapater suspension status
760
+ *
761
+ * @function iapUnsuspendAdapter
762
+ */
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
+ }
791
+ }
792
+
793
+ /**
794
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
795
+ *
796
+ * @function iapGetAdapterQueue
797
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
798
+ */
799
+ iapGetAdapterQueue(callback) {
800
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
801
+ log.trace(origin);
802
+
803
+ return this.requestHandlerInst.getQueue(callback);
804
+ }
805
+
806
+ /**
807
+ * @summary runs troubleshoot scripts for adapter
808
+ *
809
+ * @function iapTroubleshootAdapter
810
+ * @param {Object} props - the connection, healthcheck and authentication properties
811
+ * @param {boolean} persistFlag - whether the adapter properties should be updated
812
+ * @param {Adapter} adapter - adapter instance to troubleshoot
813
+ * @param {Callback} callback - callback function to return troubleshoot results
814
+ */
815
+ async iapTroubleshootAdapter(props, persistFlag, adapter, callback) {
816
+ try {
817
+ const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
818
+ if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
819
+ return callback(result);
820
+ }
821
+ return callback(null, result);
822
+ } catch (error) {
823
+ return callback(null, error);
824
+ }
825
+ }
826
+
827
+ /**
828
+ * @summary runs healthcheck script for adapter
829
+ *
830
+ * @function iapRunAdapterHealthcheck
831
+ * @param {Adapter} adapter - adapter instance to troubleshoot
832
+ * @param {Callback} callback - callback function to return healthcheck status
833
+ */
834
+ async iapRunAdapterHealthcheck(adapter, callback) {
835
+ try {
836
+ const result = await tbUtils.healthCheck(adapter);
837
+ if (result) {
838
+ return callback(result);
839
+ }
840
+ return callback(null, result);
841
+ } catch (error) {
842
+ return callback(null, error);
843
+ }
844
+ }
845
+
846
+ /**
847
+ * @summary runs connectivity check script for adapter
848
+ *
849
+ * @function iapRunAdapterConnectivity
850
+ * @param {Adapter} adapter - adapter instance to troubleshoot
851
+ * @param {Callback} callback - callback function to return connectivity status
852
+ */
853
+ async iapRunAdapterConnectivity(callback) {
854
+ try {
855
+ const { serviceItem } = await tbUtils.getAdapterConfig();
856
+ const { host } = serviceItem.properties.properties;
857
+ const result = tbUtils.runConnectivity(host, false);
858
+ if (result.failCount > 0) {
859
+ return callback(null, result);
860
+ }
861
+ return callback(result);
862
+ } catch (error) {
863
+ return callback(null, error);
864
+ }
865
+ }
866
+
867
+ /**
868
+ * @summary runs basicGet script for adapter
869
+ *
870
+ * @function iapRunAdapterBasicGet
871
+ * @param {Callback} callback - callback function to return basicGet result
872
+ */
873
+ iapRunAdapterBasicGet(callback) {
874
+ try {
875
+ const result = tbUtils.runBasicGet(false);
876
+ if (result.failCount > 0) {
877
+ return callback(null, result);
878
+ }
879
+ return callback(result);
880
+ } catch (error) {
881
+ return callback(null, error);
882
+ }
883
+ }
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
+
907
+ /**
908
+ * @summary take the entities and add them to the cache
909
+ *
910
+ * @function addEntityCache
911
+ * @param {String} entityType - the type of the entities
912
+ * @param {Array} data - the list of entities
913
+ * @param {String} key - unique key for the entities
914
+ *
915
+ * @param {Callback} callback - An array of whether the adapter can has the
916
+ * desired capability or an error
917
+ */
918
+ addEntityCache(entityType, entities, key, callback) {
919
+ const meth = 'adapterBase-addEntityCache';
920
+ const origin = `${this.id}-${meth}`;
921
+ log.trace(origin);
922
+
923
+ // list containing the items to add to the cache
924
+ const entityIds = [];
925
+
926
+ if (entities && Object.hasOwnProperty.call(entities, 'response')
927
+ && Array.isArray(entities.response)) {
928
+ for (let e = 0; e < entities.response.length; e += 1) {
929
+ entityIds.push(entities.response[e][key]);
930
+ }
931
+ }
932
+
933
+ // add the entities to the cache
934
+ return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
935
+ if (error) {
936
+ return callback(null, error);
937
+ }
938
+ if (!loaded) {
939
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
940
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
941
+ return callback(null, errorObj);
942
+ }
943
+
944
+ return callback(loaded);
945
+ });
946
+ }
947
+
948
+ /**
949
+ * @summary sees if the entity is in the entity list or not
950
+ *
951
+ * @function entityInList
952
+ * @param {String/Array} entityId - the specific entity we are looking for
953
+ * @param {Array} data - the list of entities
954
+ *
955
+ * @param {Callback} callback - An array of whether the adapter can has the
956
+ * desired capability or an error
957
+ */
958
+ entityInList(entityId, data) {
959
+ const origin = `${this.id}-adapterBase-entityInList`;
960
+ log.trace(origin);
961
+
962
+ // need to check on the entities that were passed in
963
+ if (Array.isArray(entityId)) {
964
+ const resEntity = [];
965
+
966
+ for (let e = 0; e < entityId.length; e += 1) {
967
+ if (data.includes(entityId[e])) {
968
+ resEntity.push(true);
969
+ } else {
970
+ resEntity.push(false);
971
+ }
972
+ }
973
+
974
+ return resEntity;
975
+ }
976
+
977
+ // does the entity list include the specific entity
978
+ return [data.includes(entityId)];
979
+ }
980
+
981
+ /**
982
+ * @summary prepare results for verify capability so they are true/false
983
+ *
984
+ * @function capabilityResults
985
+ * @param {Array} results - the results from the capability check
986
+ *
987
+ * @param {Callback} callback - An array of whether the adapter can has the
988
+ * desired capability or an error
989
+ */
990
+ capabilityResults(results, callback) {
991
+ const meth = 'adapterBase-capabilityResults';
992
+ const origin = `${this.id}-${meth}`;
993
+ log.trace(origin);
994
+ let locResults = results;
686
995
 
687
996
  if (locResults && locResults[0] === 'needupdate') {
688
997
  const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', ['unknown'], null, null, null);
@@ -745,6 +1054,735 @@ class AdapterBase extends EventEmitterCl {
745
1054
  return [];
746
1055
  }
747
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
+ }
748
1786
  }
749
1787
 
750
1788
  module.exports = AdapterBase;