@openfn/language-dhis2 3.0.0-0 → 3.0.0

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.
package/lib/Adaptor.js CHANGED
@@ -10,9 +10,10 @@ exports.get = get;
10
10
  exports.upsert = upsert;
11
11
  exports.discover = discover;
12
12
  exports.patch = patch;
13
- exports.del = del;
14
- exports.attrVal = attrVal;
15
- exports.attribute = attribute;
13
+ exports.destroy = destroy;
14
+ exports.findAttributeValue = findAttributeValue;
15
+ exports.attr = attr;
16
+ exports.dv = dv;
16
17
  Object.defineProperty(exports, "field", {
17
18
  enumerable: true,
18
19
  get: function () {
@@ -82,10 +83,10 @@ Object.defineProperty(exports, "http", {
82
83
 
83
84
  var _axios = _interopRequireDefault(require("axios"));
84
85
 
85
- var _languageCommon = require("@openfn/language-common");
86
-
87
86
  var _lodash = require("lodash");
88
87
 
88
+ var _languageCommon = require("@openfn/language-common");
89
+
89
90
  var _Utils = require("./Utils");
90
91
 
91
92
  var _Client = require("./Client");
@@ -178,23 +179,20 @@ _axios.default.interceptors.response.use(function (response) {
178
179
 
179
180
  return response;
180
181
  }, function (error) {
181
- try {
182
- var _details$config, _details$config2;
183
-
184
- const details = error.toJSON();
185
- if (details === null || details === void 0 ? void 0 : (_details$config = details.config) === null || _details$config === void 0 ? void 0 : _details$config.auth) details.config.auth = '--REDACTED--';
186
- if (details === null || details === void 0 ? void 0 : (_details$config2 = details.config) === null || _details$config2 === void 0 ? void 0 : _details$config2.data) details.config.data = '--REDACTED--';
182
+ var _error$config, _error$config2, _error$response, _error$response$data, _error$response2;
187
183
 
188
- _Utils.Log.error(details.message);
184
+ if ((_error$config = error.config) === null || _error$config === void 0 ? void 0 : _error$config.auth) error.config.auth = '--REDACTED--';
185
+ if ((_error$config2 = error.config) === null || _error$config2 === void 0 ? void 0 : _error$config2.data) error.config.data = '--REDACTED--';
186
+ const details = (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$data = _error$response.data) === null || _error$response$data === void 0 ? void 0 : _error$response$data.response;
189
187
 
190
- return Promise.reject(details);
191
- } catch (e) {
192
- // TODO: @Elias, why does this error sometimes already appear to be JSONified?
193
- // console.log(e) // "not JSONABLE TypeError: error.toJSON is not a function"
194
- _Utils.Log.error(error.message);
188
+ _Utils.Log.error(error.message || "That didn't work.");
195
189
 
196
- return Promise.reject(error);
197
- }
190
+ if (details) console.log(JSON.stringify(details, null, 2));
191
+ return Promise.reject({
192
+ request: error.config,
193
+ error: error.message,
194
+ response: (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.data
195
+ });
198
196
  });
199
197
  /**
200
198
  * Create a record
@@ -202,25 +200,22 @@ _axios.default.interceptors.response.use(function (response) {
202
200
  * @function
203
201
  * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`, `programs`, `events`, ...
204
202
  * @param {Object} data - Data that will be used to create a given instance of resource. To create a single instance of a resource, `data` must be a javascript object, and to create multiple instances of a resources, `data` must be an array of javascript objects.
205
- * @param {Object} [options] - Optional `options` to control the behavior of the `create` operation and to pass `import parameters` E.g. `{dryRun: true, importStrategy: CREATE}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html DHIS2 API documentation} or {@link discover}..` Defaults to `{operationName: 'create', apiVersion: null, responseType: 'json'}`
203
+ * @param {Object} [options] - Optional `options` to define URL parameters via params (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
206
204
  * @param {function} [callback] - Optional callback to handle the response
207
205
  * @returns {Operation}
208
- *
209
- * @example <caption>-a `program`</caption>
206
+ * @example <caption>a program</caption>
210
207
  * create('programs', {
211
208
  * name: 'name 20',
212
209
  * shortName: 'n20',
213
210
  * programType: 'WITHOUT_REGISTRATION',
214
211
  * });
215
- *
216
- * @example <caption>-an `event`</caption>
212
+ * @example <caption>an event</caption>
217
213
  * create('events', {
218
214
  * program: 'eBAyeGv0exc',
219
215
  * orgUnit: 'DiszpKrYNg8',
220
216
  * status: 'COMPLETED',
221
217
  * });
222
- *
223
- * @example <caption>-a `trackedEntityInstance`</caption>
218
+ * @example <caption>a trackedEntityInstance</caption>
224
219
  * create('trackedEntityInstances', {
225
220
  * orgUnit: 'TSyzvBiovKh',
226
221
  * trackedEntityType: 'nEenWmSyUEp',
@@ -231,11 +226,9 @@ _axios.default.interceptors.response.use(function (response) {
231
226
  * },
232
227
  * ]
233
228
  * });
234
- *
235
- * @example <caption>-a `dataSet`</caption>
229
+ * @example <caption>a dataSet</caption>
236
230
  * create('dataSets', { name: 'OpenFn Data Set', periodType: 'Monthly' });
237
- *
238
- * @example <caption>-a `dataSetNotification`</caption>
231
+ * @example <caption>a dataSetNotification</caption>
239
232
  * create('dataSetNotificationTemplates', {
240
233
  * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
241
234
  * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
@@ -244,8 +237,7 @@ _axios.default.interceptors.response.use(function (response) {
244
237
  * deliveryChannels: ['SMS'],
245
238
  * dataSets: [],
246
239
  * });
247
- *
248
- * @example <caption>-a `dataElement`</caption>
240
+ * @example <caption>a dataElement</caption>
249
241
  * create('dataElements', {
250
242
  * aggregationType: 'SUM',
251
243
  * domainType: 'AGGREGATE',
@@ -253,30 +245,26 @@ _axios.default.interceptors.response.use(function (response) {
253
245
  * name: 'Paracetamol',
254
246
  * shortName: 'Para',
255
247
  * });
256
- *
257
- * @example <caption>-a `dataElementGroup`</caption>
248
+ * @example <caption>a dataElementGroup</caption>
258
249
  * create('dataElementGroups', {
259
250
  * name: 'Data Element Group 1',
260
251
  * dataElements: [],
261
252
  * });
262
- *
263
- * @example <caption>-a `dataElementGroupSet`</caption>
253
+ * @example <caption>a dataElementGroupSet</caption>
264
254
  * create('dataElementGroupSets', {
265
255
  * name: 'Data Element Group Set 4',
266
256
  * dataDimension: true,
267
257
  * shortName: 'DEGS4',
268
258
  * dataElementGroups: [],
269
259
  * });
270
- *
271
- * @example <caption>-a `dataValueSet`</caption>
260
+ * @example <caption>a dataValueSet</caption>
272
261
  * create('dataValueSets', {
273
262
  * dataElement: 'f7n9E0hX8qk',
274
263
  * period: '201401',
275
264
  * orgUnit: 'DiszpKrYNg8',
276
265
  * value: '12',
277
266
  * });
278
- *
279
- * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
267
+ * @example <caption>a dataValueSet with related dataValues</caption>
280
268
  * create('dataValueSets', {
281
269
  * dataSet: 'pBOMPrpg1QX',
282
270
  * completeDate: '2014-02-03',
@@ -297,8 +285,7 @@ _axios.default.interceptors.response.use(function (response) {
297
285
  * },
298
286
  * ],
299
287
  * });
300
- *
301
- * @example <caption>-an `enrollment`</caption>
288
+ * @example <caption>an enrollment</caption>
302
289
  * create('enrollments', {
303
290
  * trackedEntityInstance: 'bmshzEacgxa',
304
291
  * orgUnit: 'TSyzvBiovKh',
@@ -309,19 +296,25 @@ _axios.default.interceptors.response.use(function (response) {
309
296
  */
310
297
 
311
298
 
312
- function create(resourceType, data, options, callback) {
299
+ function create(resourceType, data, options = {}, callback = false) {
313
300
  return state => {
314
301
  console.log(`Preparing create operation...`);
315
302
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
316
303
  data = (0, _languageCommon.expandReferences)(data)(state);
317
304
  options = (0, _languageCommon.expandReferences)(options)(state);
305
+ const {
306
+ params,
307
+ requestConfig
308
+ } = options;
318
309
  const {
319
310
  configuration
320
311
  } = state;
321
312
  return (0, _Client.request)(configuration, {
322
313
  method: 'post',
323
314
  url: (0, _Utils.generateUrl)(configuration, options, resourceType),
324
- data: (0, _Utils.nestArray)(data, resourceType)
315
+ params,
316
+ data: (0, _Utils.nestArray)(data, resourceType),
317
+ ...requestConfig
325
318
  }).then(result => {
326
319
  _Utils.Log.success(`Created ${resourceType}: ${result.headers.location}`);
327
320
 
@@ -337,17 +330,16 @@ function create(resourceType, data, options, callback) {
337
330
  * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
338
331
  * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
339
332
  * @param {Object} data - Data to update. It requires to send `all required fields` or the `full body`. If you want `partial updates`, use `patch` operation.
340
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional options for update method. Defaults to `{operationName: 'update', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
333
+ * @param {Object} [options] - Optional `options` to define URL parameters via params (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
341
334
  * @param {function} [callback] - Optional callback to handle the response
342
335
  * @returns {Operation}
343
- * @example <caption>-a program</caption>
336
+ * @example <caption>a program</caption>
344
337
  * update('programs', 'qAZJCrNJK8H', {
345
338
  * name: '14e1aa02c3f0a31618e096f2c6d03bed',
346
339
  * shortName: '14e1aa02',
347
340
  * programType: 'WITHOUT_REGISTRATION',
348
341
  * });
349
- *
350
- * @example <caption>an `event`</caption>
342
+ * @example <caption>an event</caption>
351
343
  * update('events', 'PVqUD2hvU4E', {
352
344
  * program: 'eBAyeGv0exc',
353
345
  * orgUnit: 'Ngelehun CHC',
@@ -355,8 +347,7 @@ function create(resourceType, data, options, callback) {
355
347
  * storedBy: 'admin',
356
348
  * dataValues: [],
357
349
  * });
358
- *
359
- * @example <caption>a `trackedEntityInstance`</caption>
350
+ * @example <caption>a trackedEntityInstance</caption>
360
351
  * update('trackedEntityInstances', 'IeQfgUtGPq2', {
361
352
  * created: '2015-08-06T21:12:37.256',
362
353
  * orgUnit: 'TSyzvBiovKh',
@@ -396,11 +387,9 @@ function create(resourceType, data, options, callback) {
396
387
  * },
397
388
  * ],
398
389
  * });
399
- *
400
- * @example <caption>-a `dataSet`</caption>
390
+ * @example <caption>a dataSet</caption>
401
391
  * update('dataSets', 'lyLU2wR22tC', { name: 'OpenFN Data Set', periodType: 'Weekly' });
402
- *
403
- * @example <caption>-a `dataSetNotification`</caption>
392
+ * @example <caption>a dataSetNotification</caption>
404
393
  * update('dataSetNotificationTemplates', 'VbQBwdm1wVP', {
405
394
  * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
406
395
  * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
@@ -409,8 +398,7 @@ function create(resourceType, data, options, callback) {
409
398
  * deliveryChannels: ['SMS'],
410
399
  * dataSets: [],
411
400
  * });
412
- *
413
- * @example <caption>-a `dataElement`</caption>
401
+ * @example <caption>a dataElement</caption>
414
402
  * update('dataElements', 'FTRrcoaog83', {
415
403
  * aggregationType: 'SUM',
416
404
  * domainType: 'AGGREGATE',
@@ -418,30 +406,26 @@ function create(resourceType, data, options, callback) {
418
406
  * name: 'Paracetamol',
419
407
  * shortName: 'Para',
420
408
  * });
421
- *
422
- * @example <caption>-a `dataElementGroup`</caption>
409
+ * @example <caption>a dataElementGroup</caption>
423
410
  * update('dataElementGroups', 'QrprHT61XFk', {
424
411
  * name: 'Data Element Group 1',
425
412
  * dataElements: [],
426
413
  * });
427
- *
428
- * @example <caption>-a `dataElementGroupSet`</caption>
414
+ * @example <caption>a dataElementGroupSet</caption>
429
415
  * update('dataElementGroupSets', 'VxWloRvAze8', {
430
416
  * name: 'Data Element Group Set 4',
431
417
  * dataDimension: true,
432
418
  * shortName: 'DEGS4',
433
419
  * dataElementGroups: [],
434
420
  * });
435
- *
436
- * @example <caption>-a `dataValueSet`</caption>
421
+ * @example <caption>a dataValueSet</caption>
437
422
  * update('dataValueSets', 'AsQj6cDsUq4', {
438
423
  * dataElement: 'f7n9E0hX8qk',
439
424
  * period: '201401',
440
425
  * orgUnit: 'DiszpKrYNg8',
441
426
  * value: '12',
442
427
  * });
443
- *
444
- * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
428
+ * @example <caption>a dataValueSet with related dataValues</caption>
445
429
  * update('dataValueSets', 'Ix2HsbDMLea', {
446
430
  * dataSet: 'pBOMPrpg1QX',
447
431
  * completeDate: '2014-02-03',
@@ -462,7 +446,6 @@ function create(resourceType, data, options, callback) {
462
446
  * },
463
447
  * ],
464
448
  * });
465
- *
466
449
  * @example <caption>a single enrollment</caption>
467
450
  * update('enrollments', 'CmsHzercTBa' {
468
451
  * trackedEntityInstance: 'bmshzEacgxa',
@@ -474,21 +457,26 @@ function create(resourceType, data, options, callback) {
474
457
  */
475
458
 
476
459
 
477
- function update(resourceType, path, data, options, callback) {
460
+ function update(resourceType, path, data, options = {}, callback = false) {
478
461
  return state => {
479
462
  console.log(`Preparing update operation...`);
480
463
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
481
464
  path = (0, _languageCommon.expandReferences)(path)(state);
482
465
  data = (0, _languageCommon.expandReferences)(data)(state);
483
466
  options = (0, _languageCommon.expandReferences)(options)(state);
467
+ const {
468
+ params,
469
+ requestConfig
470
+ } = options;
484
471
  const {
485
472
  configuration
486
473
  } = state;
487
474
  return (0, _Client.request)(configuration, {
488
475
  method: 'put',
489
- url: `${(0, _Utils.generateUrl)(configuration, options, resourceType)}/${path}`,
490
- // TODO: @Elias, why no "nestArray" here?
491
- data
476
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
477
+ params,
478
+ data,
479
+ ...requestConfig
492
480
  }).then(result => {
493
481
  _Utils.Log.success(`Updated ${resourceType} at ${path}`);
494
482
 
@@ -502,36 +490,50 @@ function update(resourceType, path, data, options, callback) {
502
490
  * @public
503
491
  * @function
504
492
  * @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `trackedEntityInstances`,`organisationUnits`, etc.
505
- * @param {{apiVersion: number,operationName: string,responseType: string}}[options] - `Optional` options for `getData` operation. Defaults to `{operationName: 'getData', apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
493
+ * @param {Object} query - A query object that will limit what resources are retrieved when converted into request params.
494
+ * @param {Object} [options] - Optional `options` to define URL parameters via params beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.
506
495
  * @param {function} [callback] - Optional callback to handle the response
507
496
  * @returns {Operation} state
508
- * @example <caption>Example getting one `trackedEntityInstance` with `Id` 'dNpxRu1mWG5' for a given `orgUnit(DiszpKrYNg8)`</caption>
509
- * getData('trackedEntityInstances', {
510
- * fields: '*',
511
- * ou: 'DiszpKrYNg8',
512
- * entityType: 'nEenWmSyUEp',
513
- * trackedEntityInstance: 'dNpxRu1mWG5',
497
+ * @example <caption>all data values for the 'pBOMPrpg1QX' dataset</caption>
498
+ * get('dataValueSets', {
499
+ * dataSet: 'pBOMPrpg1QX',
500
+ * orgUnit: 'DiszpKrYNg8',
501
+ * period: '201401',
502
+ * fields: '*',
503
+ * });
504
+ * @example <caption>all programs for an organization unit</caption>
505
+ * get('programs', { orgUnit: 'TSyzvBiovKh', fields: '*' });
506
+ * @example <caption>a single tracked entity instance by a unique external ID</caption>
507
+ * get('trackedEntityInstances', {
508
+ * ou: 'DiszpKrYNg8',
509
+ * filter: ['flGbXLXCrEo:Eq:124', 'w75KJ2mc4zz:Eq:John'],
514
510
  * });
515
511
  */
516
- // TODO: @Elias, I'm not sure "options" is the right name for the second arg here.
517
- // Isn't this more like the filters that you're using to find the right resources?
518
512
 
519
513
 
520
- function get(resourceType, options, callback) {
514
+ function get(resourceType, query, options = {}, callback = false) {
521
515
  return state => {
522
- console.log(`Preparing get operation...`);
516
+ console.log('Preparing get operation...');
523
517
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
518
+ query = (0, _languageCommon.expandReferences)(query)(state);
524
519
  options = (0, _languageCommon.expandReferences)(options)(state);
520
+ const {
521
+ params,
522
+ requestConfig
523
+ } = options;
525
524
  const {
526
525
  configuration
527
526
  } = state;
528
527
  return (0, _Client.request)(configuration, {
529
528
  method: 'get',
530
529
  url: (0, _Utils.generateUrl)(configuration, options, resourceType),
531
- params: (0, _Utils.buildUrlParams)(options),
532
- responseType: 'json'
530
+ params: { ...query,
531
+ ...params
532
+ },
533
+ responseType: 'json',
534
+ ...requestConfig
533
535
  }).then(result => {
534
- _Utils.Log.success(`Retrieved ${result.data[resourceType].length} ${resourceType}.`);
536
+ _Utils.Log.success(`Retrieved ${resourceType}`);
535
537
 
536
538
  return (0, _Utils.handleResponse)(result, state, callback);
537
539
  });
@@ -541,46 +543,56 @@ function get(resourceType, options, callback) {
541
543
  * Upsert a record. A generic helper function used to atomically either insert a row, or on the basis of the row already existing, UPDATE that existing row instead.
542
544
  * @public
543
545
  * @function
544
- * @param {string} resourceType - The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`
545
- * @param {Object} data - The update data containing new values
546
- * @param {{replace:boolean, apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{replace: false, apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
546
+ * @param {string} resourceType - The type of a resource to `upsert`. E.g. `trackedEntityInstances`
547
+ * @param {Object} query - A query object that allows to uniquely identify the resource to update. If no matches found, then the resource will be created.
548
+ * @param {Object} data - The data to use for update or create depending on the result of the query.
549
+ * @param {{ apiVersion: object, requestConfig: object, params: object }} [options] - Optional configuration that will be applied to both the `get` and the `create` or `update` operations.
547
550
  * @param {function} [callback] - Optional callback to handle the response
548
551
  * @throws {RangeError} - Throws range error
549
552
  * @returns {Operation}
550
553
  * @example <caption>Example `expression.js` of upsert</caption>
551
- * upsert(
552
- * 'trackedEntityInstances',
554
+ * upsert('trackedEntityInstances', {
555
+ * ou: 'TSyzvBiovKh',
556
+ * filter: ['w75KJ2mc4zz:Eq:Qassim'],
557
+ * }, {
558
+ * orgUnit: 'TSyzvBiovKh',
559
+ * trackedEntityType: 'nEenWmSyUEp',
560
+ * attributes: [
553
561
  * {
554
- * attributeId: 'lZGmxYbs97q',
555
- * attributeValue: state =>
556
- * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
557
- * .value,
562
+ * attribute: 'w75KJ2mc4zz',
563
+ * value: 'Qassim',
558
564
  * },
559
- * state.data,
560
- * { ou: 'TSyzvBiovKh' }
561
- * );
562
- * @todo Tweak/refine to mimic implementation based on the following inspiration: {@link https://sqlite.org/lang_upsert.html sqlite upsert} and {@link https://wiki.postgresql.org/wiki/UPSERT postgresql upsert}
563
- * @todo Test implementation for upserting metadata
564
- * @todo Test implementation for upserting data values
565
- * @todo Implement the updateCondition
565
+ * ],
566
+ * });
566
567
  */
567
568
 
568
569
 
569
- function upsert(resourceType, data, options, callback) {
570
+ function upsert(resourceType, // resourceType supplied to both the `get` and the `create/update`
571
+ query, // query supplied to the `get`
572
+ data, // data supplied to the `create/update`
573
+ options = {}, // options supplied to both the `get` and the `create/update`
574
+ callback = false // callback for the upsert itself.
575
+ ) {
570
576
  return state => {
571
577
  console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
572
- return get(resourceType, options)(state).then(resp => {
578
+ return get(resourceType, query, options)(state).then(resp => {
573
579
  const resources = resp.data[resourceType];
574
580
 
575
581
  if (resources.length > 1) {
576
582
  throw new RangeError(`Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`);
577
583
  } else if (resources.length <= 0) {
578
- return create(resourceType, data, options, callback)(state);
584
+ return create(resourceType, data, options)(state);
579
585
  } else {
580
- const pathName = resourceType === 'trackedEntityInstances' ? 'trackedEntityInstance' : 'id';
581
- const path = resources[0][pathName];
582
- return update(resourceType, path, data, options, callback)(state);
586
+ // Pick out the first (and only) resource in the array and grab its
587
+ // ID to be used in the subsequent `update` by the path determined
588
+ // by the `selectId(...)` function.
589
+ const path = resources[0][(0, _Utils.selectId)(resourceType)];
590
+ return update(resourceType, path, data, options)(state);
583
591
  }
592
+ }).then(result => {
593
+ _Utils.Log.success(`Performed a "composed upsert" on ${resourceType}`);
594
+
595
+ return (0, _Utils.handleResponse)(result, state, callback);
584
596
  });
585
597
  };
586
598
  }
@@ -591,7 +603,7 @@ function upsert(resourceType, data, options, callback) {
591
603
  * @param {string} httpMethod - The HTTP to inspect parameter usage for a given endpoint, e.g., `get`, `post`,`put`,`patch`,`delete`
592
604
  * @param {string} endpoint - The path for a given endpoint. E.g. `/trackedEntityInstances` or `/dataValueSets`
593
605
  * @returns {Operation}
594
- * @example <caption>Example getting a list of `parameters allowed` on a given `endpoint` for specific `http method`</caption>
606
+ * @example <caption>a list of parameters allowed on a given endpoint for specific http method</caption>
595
607
  * discover('post', '/trackedEntityInstances')
596
608
  */
597
609
 
@@ -650,65 +662,40 @@ function discover(httpMethod, endpoint) {
650
662
  * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
651
663
  * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
652
664
  * @param {Object} data - Data to update. Include only the fields you want to update. E.g. `{name: "New Name"}`
653
- * @param {Object} [params] - Optional `update` parameters e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}
654
- * @param {{apiVersion: number,operationName: string,responseType: string}} [options] - Optional options for update method. Defaults to `{operationName: 'patch', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
665
+ * @param {Object} [options] - Optional configuration, including params for the update ({preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}). Defaults to `{operationName: 'patch', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
655
666
  * @param {function} [callback] - Optional callback to handle the response
656
667
  * @returns {Operation}
657
- * @example <caption>Example `patching` a `data element`</caption>
658
- * patch('dataElements', 'FTRrcoaog83',
659
- * {
660
- * name: 'New Name',
661
- * });
668
+ * @example <caption>a dataElement</caption>
669
+ * patch('dataElements', 'FTRrcoaog83', { name: 'New Name' });
662
670
  */
663
671
  // TODO: @Elias, can this be deleted in favor of update? How does DHIS2 handle PATCH vs PUT?
672
+ // I need to investigate on this. But I think DHIS2 forces to send all properties back when we do an update. If that's confirmed then this may be needed.
664
673
 
665
674
 
666
- function patch(resourceType, path, data, params, options, callback) {
675
+ function patch(resourceType, path, data, options = {}, callback = false) {
667
676
  return state => {
668
- var _options$operationNam, _options, _options$responseType, _options2, _queryParams, _queryParams2, _options$apiVersion, _options3, _CONTENT_TYPES$respon;
669
-
677
+ console.log('Preparing patch operation...');
670
678
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
671
679
  path = (0, _languageCommon.expandReferences)(path)(state);
672
- const body = (0, _languageCommon.expandReferences)(data)(state);
673
- params = (0, _languageCommon.expandReferences)(params)(state);
680
+ data = (0, _languageCommon.expandReferences)(data)(state);
674
681
  options = (0, _languageCommon.expandReferences)(options)(state);
675
- const operationName = (_options$operationNam = (_options = options) === null || _options === void 0 ? void 0 : _options.operationName) !== null && _options$operationNam !== void 0 ? _options$operationNam : 'patch';
676
682
  const {
677
- username,
678
- password,
679
- hostUrl
680
- } = state.configuration;
681
- const responseType = (_options$responseType = (_options2 = options) === null || _options2 === void 0 ? void 0 : _options2.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : 'json';
682
- let queryParams = params;
683
- const filters = (_queryParams = queryParams) === null || _queryParams === void 0 ? void 0 : _queryParams.filters;
684
- (_queryParams2 = queryParams) === null || _queryParams2 === void 0 ? true : delete _queryParams2.filters;
685
- queryParams = new URLSearchParams(queryParams);
686
- filters === null || filters === void 0 ? void 0 : filters.map(f => queryParams.append('filter', f));
687
- const apiVersion = (_options$apiVersion = (_options3 = options) === null || _options3 === void 0 ? void 0 : _options3.apiVersion) !== null && _options$apiVersion !== void 0 ? _options$apiVersion : state.configuration.apiVersion;
688
- const url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
689
- const headers = {
690
- Accept: (_CONTENT_TYPES$respon = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon !== void 0 ? _CONTENT_TYPES$respon : 'application/json'
691
- };
692
- return _axios.default.request({
693
- method: 'PATCH',
694
- url,
695
- auth: {
696
- username,
697
- password
698
- },
699
- params: queryParams,
700
- data: body,
701
- headers
683
+ params,
684
+ requestConfig
685
+ } = options;
686
+ const {
687
+ configuration
688
+ } = state;
689
+ return (0, _Client.request)(configuration, {
690
+ method: 'patch',
691
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
692
+ params,
693
+ data,
694
+ ...requestConfig
702
695
  }).then(result => {
703
- let resultObject = {
704
- status: result.status,
705
- statusText: result.statusText
706
- };
696
+ _Utils.Log.success(`Patched ${resourceType} at ${path}`);
707
697
 
708
- _Utils.Log.success(`${operationName} succeeded. Updated ${resourceType}.\nSummary:\n${(0, _Utils.prettyJson)(resultObject)}`);
709
-
710
- if (callback) return callback((0, _languageCommon.composeNextState)(state, resultObject));
711
- return (0, _languageCommon.composeNextState)(state, resultObject);
698
+ return (0, _Utils.handleResponse)(result, state, callback);
712
699
  });
713
700
  };
714
701
  }
@@ -719,57 +706,38 @@ function patch(resourceType, path, data, params, options, callback) {
719
706
  * @param {string} resourceType - The type of resource to be deleted. E.g. `trackedEntityInstances`, `organisationUnits`, etc.
720
707
  * @param {string} path - Can be an `id` of an `object` or `path` to the `nested object` to `delete`.
721
708
  * @param {Object} [data] - Optional. This is useful when you want to remove multiple objects from a collection in one request. You can send `data` as, for example, `{"identifiableObjects": [{"id": "IDA"}, {"id": "IDB"}, {"id": "IDC"}]}`. See more {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#deleting-objects on DHIS2 API docs}
722
- * @param {Object} [params] - Optional `update` parameters e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}
723
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `del` operation. Defaults to `{operationName: 'delete', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
709
+ * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `del` operation including params e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}. Defaults to `{operationName: 'delete', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
724
710
  * @param {function} [callback] - Optional callback to handle the response
725
711
  * @returns {Operation}
726
- * @example <caption>Example`deleting` a `tracked entity instance`</caption>
727
- * del('trackedEntityInstances', 'LcRd6Nyaq7T');
712
+ * @example <caption>a tracked entity instance</caption>
713
+ * destroy('trackedEntityInstances', 'LcRd6Nyaq7T');
728
714
  */
729
- // TODO: @Elias, can this be implemented using the same pattern as update but without data?
730
715
 
731
716
 
732
- function del(resourceType, path, data, params, options, callback) {
717
+ function destroy(resourceType, path, data = null, options = {}, callback = false) {
733
718
  return state => {
734
- var _options$operationNam2, _options4, _options$responseType2, _options5, _queryParams3, _queryParams4, _options$apiVersion2, _options6, _CONTENT_TYPES$respon2;
735
-
719
+ console.log('Preparing destroy operation...');
736
720
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
737
721
  path = (0, _languageCommon.expandReferences)(path)(state);
738
- const body = (0, _languageCommon.expandReferences)(data)(state);
739
- params = (0, _languageCommon.expandReferences)(params)(state);
722
+ data = (0, _languageCommon.expandReferences)(data)(state);
740
723
  options = (0, _languageCommon.expandReferences)(options)(state);
741
- const operationName = (_options$operationNam2 = (_options4 = options) === null || _options4 === void 0 ? void 0 : _options4.operationName) !== null && _options$operationNam2 !== void 0 ? _options$operationNam2 : 'delete';
742
724
  const {
743
- username,
744
- password,
745
- hostUrl
746
- } = state.configuration;
747
- const responseType = (_options$responseType2 = (_options5 = options) === null || _options5 === void 0 ? void 0 : _options5.responseType) !== null && _options$responseType2 !== void 0 ? _options$responseType2 : 'json';
748
- let queryParams = params;
749
- const filters = (_queryParams3 = queryParams) === null || _queryParams3 === void 0 ? void 0 : _queryParams3.filters;
750
- (_queryParams4 = queryParams) === null || _queryParams4 === void 0 ? true : delete _queryParams4.filters;
751
- queryParams = new URLSearchParams(queryParams);
752
- filters === null || filters === void 0 ? void 0 : filters.map(f => queryParams.append('filter', f));
753
- const apiVersion = (_options$apiVersion2 = (_options6 = options) === null || _options6 === void 0 ? void 0 : _options6.apiVersion) !== null && _options$apiVersion2 !== void 0 ? _options$apiVersion2 : state.configuration.apiVersion;
754
- const headers = {
755
- Accept: (_CONTENT_TYPES$respon2 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon2 !== void 0 ? _CONTENT_TYPES$respon2 : 'application/json'
756
- };
757
- const url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
758
- return _axios.default.request({
759
- method: 'DELETE',
760
- url,
761
- auth: {
762
- username,
763
- password
764
- },
765
- params: queryParams,
766
- data: body,
767
- headers
725
+ params,
726
+ requestConfig
727
+ } = options;
728
+ const {
729
+ configuration
730
+ } = state;
731
+ return (0, _Client.request)({
732
+ method: 'delete',
733
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
734
+ params,
735
+ data,
736
+ ...requestConfig
768
737
  }).then(result => {
769
- _Utils.Log.success(`${operationName} succeeded. DELETED ${resourceType}.\nSummary:\n${(0, _Utils.prettyJson)(result.data)}`);
738
+ _Utils.Log.success(`Deleted ${resourceType} at ${path}`);
770
739
 
771
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
772
- return (0, _languageCommon.composeNextState)(state, result.data);
740
+ return (0, _Utils.handleResponse)(result, state, callback);
773
741
  });
774
742
  };
775
743
  }
@@ -777,34 +745,52 @@ function del(resourceType, path, data, params, options, callback) {
777
745
  * Gets an attribute value by its case-insensitive display name
778
746
  * @public
779
747
  * @example
780
- * attrVal(tei.attributes, 'first name')
748
+ * findAttributeValue(state.data.trackedEntityInstances[0], 'first name')
781
749
  * @function
782
- * @param {Object} tei - A tracked entity instance (TEI) object
783
- * @param {string} attributeName - The 'displayName' to search for in the TEI's attributes
750
+ * @param {Object} trackedEntityInstance - A tracked entity instance (TEI) object
751
+ * @param {string} attributeDisplayName - The 'displayName' to search for in the TEI's attributes
784
752
  * @returns {string}
785
753
  */
786
754
 
787
755
 
788
- function attrVal(tei, attributeName) {
789
- var _tei$attributes, _tei$attributes$find;
756
+ function findAttributeValue(trackedEntityInstance, attributeDisplayName) {
757
+ var _trackedEntityInstanc, _trackedEntityInstanc2;
790
758
 
791
- return tei === null || tei === void 0 ? void 0 : (_tei$attributes = tei.attributes) === null || _tei$attributes === void 0 ? void 0 : (_tei$attributes$find = _tei$attributes.find(a => (a === null || a === void 0 ? void 0 : a.displayName.toLowerCase()) == attributeName.toLowerCase())) === null || _tei$attributes$find === void 0 ? void 0 : _tei$attributes$find.value;
759
+ return trackedEntityInstance === null || trackedEntityInstance === void 0 ? void 0 : (_trackedEntityInstanc = trackedEntityInstance.attributes) === null || _trackedEntityInstanc === void 0 ? void 0 : (_trackedEntityInstanc2 = _trackedEntityInstanc.find(a => (a === null || a === void 0 ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase())) === null || _trackedEntityInstanc2 === void 0 ? void 0 : _trackedEntityInstanc2.value;
792
760
  }
793
761
  /**
794
762
  * Converts an attribute ID and value into a DSHI2 attribute object
795
763
  * @public
796
764
  * @example
797
- * attribute('w75KJ2mc4zz', 'Elias')
765
+ * attr('w75KJ2mc4zz', 'Elias')
766
+ * @function
767
+ * @param {string} attribute - A tracked entity instance (TEI) attribute ID.
768
+ * @param {string} value - The value for that attribute.
769
+ * @returns {object}
770
+ */
771
+
772
+
773
+ function attr(attribute, value) {
774
+ return {
775
+ attribute,
776
+ value
777
+ };
778
+ }
779
+ /**
780
+ * Converts a dataElement and value into a DSHI2 dataValue object
781
+ * @public
782
+ * @example
783
+ * dv('f7n9E0hX8qk', 12)
798
784
  * @function
799
- * @param {string} attributeId - A tracked entity instance (TEI) attribute ID.
800
- * @param {string} attributeValue - The value for that attribute.
785
+ * @param {string} dataElement - A data element ID.
786
+ * @param {string} value - The value for that data element.
801
787
  * @returns {object}
802
788
  */
803
789
 
804
790
 
805
- function attribute(attributeId, attributeValue) {
791
+ function dv(dataElement, value) {
806
792
  return {
807
- attribute: attributeId,
808
- value: attributeValue
793
+ dataElement,
794
+ value
809
795
  };
810
796
  }