@openfn/language-dhis2 3.0.0-0 → 3.0.0-2

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/ast.json CHANGED
@@ -41,7 +41,7 @@
41
41
  },
42
42
  {
43
43
  "title": "param",
44
- "description": "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'}`",
44
+ "description": "Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.",
45
45
  "type": {
46
46
  "type": "OptionalType",
47
47
  "expression": {
@@ -181,37 +181,12 @@
181
181
  },
182
182
  {
183
183
  "title": "param",
184
- "description": "Optional options for update method. Defaults to `{operationName: 'update', apiVersion: state.configuration.apiVersion, responseType: 'json'}`",
184
+ "description": "Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.",
185
185
  "type": {
186
186
  "type": "OptionalType",
187
187
  "expression": {
188
- "type": "RecordType",
189
- "fields": [
190
- {
191
- "type": "FieldType",
192
- "key": "apiVersion",
193
- "value": {
194
- "type": "NameExpression",
195
- "name": "number"
196
- }
197
- },
198
- {
199
- "type": "FieldType",
200
- "key": "operationName",
201
- "value": {
202
- "type": "NameExpression",
203
- "name": "string"
204
- }
205
- },
206
- {
207
- "type": "FieldType",
208
- "key": "resourceType",
209
- "value": {
210
- "type": "NameExpression",
211
- "name": "string"
212
- }
213
- }
214
- ]
188
+ "type": "NameExpression",
189
+ "name": "Object"
215
190
  }
216
191
  },
217
192
  "name": "options"
@@ -299,6 +274,7 @@
299
274
  "name": "get",
300
275
  "params": [
301
276
  "resourceType",
277
+ "filters",
302
278
  "options",
303
279
  "callback"
304
280
  ],
@@ -326,150 +302,21 @@
326
302
  },
327
303
  {
328
304
  "title": "param",
329
- "description": "`Optional` options for `getData` operation. Defaults to `{operationName: 'getData', apiVersion: state.configuration.apiVersion, responseType: 'json'}`.",
330
- "type": {
331
- "type": "OptionalType",
332
- "expression": {
333
- "type": "RecordType",
334
- "fields": [
335
- {
336
- "type": "FieldType",
337
- "key": "apiVersion",
338
- "value": {
339
- "type": "NameExpression",
340
- "name": "number"
341
- }
342
- },
343
- {
344
- "type": "FieldType",
345
- "key": "operationName",
346
- "value": {
347
- "type": "NameExpression",
348
- "name": "string"
349
- }
350
- },
351
- {
352
- "type": "FieldType",
353
- "key": "responseType",
354
- "value": {
355
- "type": "NameExpression",
356
- "name": "string"
357
- }
358
- }
359
- ]
360
- }
361
- },
362
- "name": "options"
363
- },
364
- {
365
- "title": "param",
366
- "description": "Optional callback to handle the response",
367
- "type": {
368
- "type": "OptionalType",
369
- "expression": {
370
- "type": "NameExpression",
371
- "name": "function"
372
- }
373
- },
374
- "name": "callback"
375
- },
376
- {
377
- "title": "returns",
378
- "description": "state",
379
- "type": {
380
- "type": "NameExpression",
381
- "name": "Operation"
382
- }
383
- },
384
- {
385
- "title": "example",
386
- "description": "getData('trackedEntityInstances', {\n fields: '*',\n ou: 'DiszpKrYNg8',\n entityType: 'nEenWmSyUEp',\n trackedEntityInstance: 'dNpxRu1mWG5',\n});",
387
- "caption": "Example getting one `trackedEntityInstance` with `Id` 'dNpxRu1mWG5' for a given `orgUnit(DiszpKrYNg8)`"
388
- }
389
- ]
390
- },
391
- "valid": true
392
- },
393
- {
394
- "name": "upsert",
395
- "params": [
396
- "resourceType",
397
- "data",
398
- "options",
399
- "callback"
400
- ],
401
- "docs": {
402
- "description": "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.",
403
- "tags": [
404
- {
405
- "title": "public",
406
- "description": null,
407
- "type": null
408
- },
409
- {
410
- "title": "function",
411
- "description": null,
412
- "name": null
413
- },
414
- {
415
- "title": "param",
416
- "description": "The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`",
417
- "type": {
418
- "type": "NameExpression",
419
- "name": "string"
420
- },
421
- "name": "resourceType"
422
- },
423
- {
424
- "title": "param",
425
- "description": "The update data containing new values",
305
+ "description": "Filters to limit what resources are retrieved.",
426
306
  "type": {
427
307
  "type": "NameExpression",
428
308
  "name": "Object"
429
309
  },
430
- "name": "data"
310
+ "name": "filters"
431
311
  },
432
312
  {
433
313
  "title": "param",
434
- "description": "`Optional` options for `upsertTEI` operation. Defaults to `{replace: false, apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.",
314
+ "description": "Optional `options` to define URL parameters beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.",
435
315
  "type": {
436
316
  "type": "OptionalType",
437
317
  "expression": {
438
- "type": "RecordType",
439
- "fields": [
440
- {
441
- "type": "FieldType",
442
- "key": "replace",
443
- "value": {
444
- "type": "NameExpression",
445
- "name": "boolean"
446
- }
447
- },
448
- {
449
- "type": "FieldType",
450
- "key": "apiVersion",
451
- "value": {
452
- "type": "NameExpression",
453
- "name": "number"
454
- }
455
- },
456
- {
457
- "type": "FieldType",
458
- "key": "strict",
459
- "value": {
460
- "type": "NameExpression",
461
- "name": "boolean"
462
- }
463
- },
464
- {
465
- "type": "FieldType",
466
- "key": "responseType",
467
- "value": {
468
- "type": "NameExpression",
469
- "name": "string"
470
- }
471
- }
472
- ]
318
+ "type": "NameExpression",
319
+ "name": "Object"
473
320
  }
474
321
  },
475
322
  "name": "options"
@@ -486,17 +333,9 @@
486
333
  },
487
334
  "name": "callback"
488
335
  },
489
- {
490
- "title": "throws",
491
- "description": "Throws range error",
492
- "type": {
493
- "type": "NameExpression",
494
- "name": "RangeError"
495
- }
496
- },
497
336
  {
498
337
  "title": "returns",
499
- "description": null,
338
+ "description": "state",
500
339
  "type": {
501
340
  "type": "NameExpression",
502
341
  "name": "Operation"
@@ -504,24 +343,13 @@
504
343
  },
505
344
  {
506
345
  "title": "example",
507
- "description": "upsert(\n 'trackedEntityInstances',\n {\n attributeId: 'lZGmxYbs97q',\n attributeValue: state =>\n state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')\n .value,\n },\n state.data,\n { ou: 'TSyzvBiovKh' }\n);",
508
- "caption": "Example `expression.js` of upsert"
509
- },
510
- {
511
- "title": "todo",
512
- "description": "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}"
346
+ "description": "get('dataValueSets', {\n dataSet: 'pBOMPrpg1QX',\n orgUnit: 'DiszpKrYNg8',\n period: '201401',\n fields: '*',\n});",
347
+ "caption": "Get all data values for the 'pBOMPrpg1QX' dataset."
513
348
  },
514
349
  {
515
- "title": "todo",
516
- "description": "Test implementation for upserting metadata"
517
- },
518
- {
519
- "title": "todo",
520
- "description": "Test implementation for upserting data values"
521
- },
522
- {
523
- "title": "todo",
524
- "description": "Implement the updateCondition"
350
+ "title": "example",
351
+ "description": "get('programs', { orgUnit: 'TSyzvBiovKh', fields: '*' });",
352
+ "caption": "get all programs for an organization unit"
525
353
  }
526
354
  ]
527
355
  },
package/lib/Adaptor.js CHANGED
@@ -7,7 +7,6 @@ exports.execute = execute;
7
7
  exports.create = create;
8
8
  exports.update = update;
9
9
  exports.get = get;
10
- exports.upsert = upsert;
11
10
  exports.discover = discover;
12
11
  exports.patch = patch;
13
12
  exports.del = del;
@@ -178,23 +177,20 @@ _axios.default.interceptors.response.use(function (response) {
178
177
 
179
178
  return response;
180
179
  }, function (error) {
181
- try {
182
- var _details$config, _details$config2;
180
+ var _error$config, _error$config2, _error$response, _error$response$data, _error$response2;
183
181
 
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
+ if ((_error$config = error.config) === null || _error$config === void 0 ? void 0 : _error$config.auth) error.config.auth = '--REDACTED--';
183
+ if ((_error$config2 = error.config) === null || _error$config2 === void 0 ? void 0 : _error$config2.data) error.config.data = '--REDACTED--';
184
+ 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;
187
185
 
188
- _Utils.Log.error(details.message);
186
+ _Utils.Log.error(error.message || "That didn't work.");
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);
195
-
196
- return Promise.reject(error);
197
- }
188
+ if (details) console.log(JSON.stringify(details, null, 2));
189
+ return Promise.reject({
190
+ request: error.config,
191
+ error: error.message,
192
+ response: (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.data
193
+ });
198
194
  });
199
195
  /**
200
196
  * Create a record
@@ -202,24 +198,21 @@ _axios.default.interceptors.response.use(function (response) {
202
198
  * @function
203
199
  * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`, `programs`, `events`, ...
204
200
  * @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'}`
201
+ * @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.
206
202
  * @param {function} [callback] - Optional callback to handle the response
207
203
  * @returns {Operation}
208
- *
209
204
  * @example <caption>-a `program`</caption>
210
205
  * create('programs', {
211
206
  * name: 'name 20',
212
207
  * shortName: 'n20',
213
208
  * programType: 'WITHOUT_REGISTRATION',
214
209
  * });
215
- *
216
210
  * @example <caption>-an `event`</caption>
217
211
  * create('events', {
218
212
  * program: 'eBAyeGv0exc',
219
213
  * orgUnit: 'DiszpKrYNg8',
220
214
  * status: 'COMPLETED',
221
215
  * });
222
- *
223
216
  * @example <caption>-a `trackedEntityInstance`</caption>
224
217
  * create('trackedEntityInstances', {
225
218
  * orgUnit: 'TSyzvBiovKh',
@@ -231,10 +224,8 @@ _axios.default.interceptors.response.use(function (response) {
231
224
  * },
232
225
  * ]
233
226
  * });
234
- *
235
227
  * @example <caption>-a `dataSet`</caption>
236
228
  * create('dataSets', { name: 'OpenFn Data Set', periodType: 'Monthly' });
237
- *
238
229
  * @example <caption>-a `dataSetNotification`</caption>
239
230
  * create('dataSetNotificationTemplates', {
240
231
  * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
@@ -244,7 +235,6 @@ _axios.default.interceptors.response.use(function (response) {
244
235
  * deliveryChannels: ['SMS'],
245
236
  * dataSets: [],
246
237
  * });
247
- *
248
238
  * @example <caption>-a `dataElement`</caption>
249
239
  * create('dataElements', {
250
240
  * aggregationType: 'SUM',
@@ -253,13 +243,11 @@ _axios.default.interceptors.response.use(function (response) {
253
243
  * name: 'Paracetamol',
254
244
  * shortName: 'Para',
255
245
  * });
256
- *
257
246
  * @example <caption>-a `dataElementGroup`</caption>
258
247
  * create('dataElementGroups', {
259
248
  * name: 'Data Element Group 1',
260
249
  * dataElements: [],
261
250
  * });
262
- *
263
251
  * @example <caption>-a `dataElementGroupSet`</caption>
264
252
  * create('dataElementGroupSets', {
265
253
  * name: 'Data Element Group Set 4',
@@ -267,7 +255,6 @@ _axios.default.interceptors.response.use(function (response) {
267
255
  * shortName: 'DEGS4',
268
256
  * dataElementGroups: [],
269
257
  * });
270
- *
271
258
  * @example <caption>-a `dataValueSet`</caption>
272
259
  * create('dataValueSets', {
273
260
  * dataElement: 'f7n9E0hX8qk',
@@ -275,7 +262,6 @@ _axios.default.interceptors.response.use(function (response) {
275
262
  * orgUnit: 'DiszpKrYNg8',
276
263
  * value: '12',
277
264
  * });
278
- *
279
265
  * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
280
266
  * create('dataValueSets', {
281
267
  * dataSet: 'pBOMPrpg1QX',
@@ -297,7 +283,6 @@ _axios.default.interceptors.response.use(function (response) {
297
283
  * },
298
284
  * ],
299
285
  * });
300
- *
301
286
  * @example <caption>-an `enrollment`</caption>
302
287
  * create('enrollments', {
303
288
  * trackedEntityInstance: 'bmshzEacgxa',
@@ -315,13 +300,19 @@ function create(resourceType, data, options, callback) {
315
300
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
316
301
  data = (0, _languageCommon.expandReferences)(data)(state);
317
302
  options = (0, _languageCommon.expandReferences)(options)(state);
303
+ const {
304
+ params,
305
+ requestConfig
306
+ } = options || {};
318
307
  const {
319
308
  configuration
320
309
  } = state;
321
310
  return (0, _Client.request)(configuration, {
322
311
  method: 'post',
323
312
  url: (0, _Utils.generateUrl)(configuration, options, resourceType),
324
- data: (0, _Utils.nestArray)(data, resourceType)
313
+ params: params && (0, _Utils.buildUrlParams)(params),
314
+ data: (0, _Utils.nestArray)(data, resourceType),
315
+ ...requestConfig
325
316
  }).then(result => {
326
317
  _Utils.Log.success(`Created ${resourceType}: ${result.headers.location}`);
327
318
 
@@ -337,7 +328,7 @@ function create(resourceType, data, options, callback) {
337
328
  * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
338
329
  * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
339
330
  * @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'}`
331
+ * @param {Object} [options] - Optional `options` to define URL parameters (E.g. `filters`, `dimensions` and `import parameters`), axios configurations (E.g. `auth`) and DHIS 2 api version to use.
341
332
  * @param {function} [callback] - Optional callback to handle the response
342
333
  * @returns {Operation}
343
334
  * @example <caption>-a program</caption>
@@ -346,7 +337,6 @@ function create(resourceType, data, options, callback) {
346
337
  * shortName: '14e1aa02',
347
338
  * programType: 'WITHOUT_REGISTRATION',
348
339
  * });
349
- *
350
340
  * @example <caption>an `event`</caption>
351
341
  * update('events', 'PVqUD2hvU4E', {
352
342
  * program: 'eBAyeGv0exc',
@@ -355,7 +345,6 @@ function create(resourceType, data, options, callback) {
355
345
  * storedBy: 'admin',
356
346
  * dataValues: [],
357
347
  * });
358
- *
359
348
  * @example <caption>a `trackedEntityInstance`</caption>
360
349
  * update('trackedEntityInstances', 'IeQfgUtGPq2', {
361
350
  * created: '2015-08-06T21:12:37.256',
@@ -396,10 +385,8 @@ function create(resourceType, data, options, callback) {
396
385
  * },
397
386
  * ],
398
387
  * });
399
- *
400
388
  * @example <caption>-a `dataSet`</caption>
401
389
  * update('dataSets', 'lyLU2wR22tC', { name: 'OpenFN Data Set', periodType: 'Weekly' });
402
- *
403
390
  * @example <caption>-a `dataSetNotification`</caption>
404
391
  * update('dataSetNotificationTemplates', 'VbQBwdm1wVP', {
405
392
  * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
@@ -409,7 +396,6 @@ function create(resourceType, data, options, callback) {
409
396
  * deliveryChannels: ['SMS'],
410
397
  * dataSets: [],
411
398
  * });
412
- *
413
399
  * @example <caption>-a `dataElement`</caption>
414
400
  * update('dataElements', 'FTRrcoaog83', {
415
401
  * aggregationType: 'SUM',
@@ -418,13 +404,11 @@ function create(resourceType, data, options, callback) {
418
404
  * name: 'Paracetamol',
419
405
  * shortName: 'Para',
420
406
  * });
421
- *
422
407
  * @example <caption>-a `dataElementGroup`</caption>
423
408
  * update('dataElementGroups', 'QrprHT61XFk', {
424
409
  * name: 'Data Element Group 1',
425
410
  * dataElements: [],
426
411
  * });
427
- *
428
412
  * @example <caption>-a `dataElementGroupSet`</caption>
429
413
  * update('dataElementGroupSets', 'VxWloRvAze8', {
430
414
  * name: 'Data Element Group Set 4',
@@ -432,7 +416,6 @@ function create(resourceType, data, options, callback) {
432
416
  * shortName: 'DEGS4',
433
417
  * dataElementGroups: [],
434
418
  * });
435
- *
436
419
  * @example <caption>-a `dataValueSet`</caption>
437
420
  * update('dataValueSets', 'AsQj6cDsUq4', {
438
421
  * dataElement: 'f7n9E0hX8qk',
@@ -440,7 +423,6 @@ function create(resourceType, data, options, callback) {
440
423
  * orgUnit: 'DiszpKrYNg8',
441
424
  * value: '12',
442
425
  * });
443
- *
444
426
  * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
445
427
  * update('dataValueSets', 'Ix2HsbDMLea', {
446
428
  * dataSet: 'pBOMPrpg1QX',
@@ -462,7 +444,6 @@ function create(resourceType, data, options, callback) {
462
444
  * },
463
445
  * ],
464
446
  * });
465
- *
466
447
  * @example <caption>a single enrollment</caption>
467
448
  * update('enrollments', 'CmsHzercTBa' {
468
449
  * trackedEntityInstance: 'bmshzEacgxa',
@@ -481,14 +462,19 @@ function update(resourceType, path, data, options, callback) {
481
462
  path = (0, _languageCommon.expandReferences)(path)(state);
482
463
  data = (0, _languageCommon.expandReferences)(data)(state);
483
464
  options = (0, _languageCommon.expandReferences)(options)(state);
465
+ const {
466
+ params,
467
+ requestConfig
468
+ } = options || {};
484
469
  const {
485
470
  configuration
486
471
  } = state;
487
472
  return (0, _Client.request)(configuration, {
488
473
  method: 'put',
489
474
  url: `${(0, _Utils.generateUrl)(configuration, options, resourceType)}/${path}`,
490
- // TODO: @Elias, why no "nestArray" here?
491
- data
475
+ params: params && (0, _Utils.buildUrlParams)(params),
476
+ data,
477
+ ...requestConfig
492
478
  }).then(result => {
493
479
  _Utils.Log.success(`Updated ${resourceType} at ${path}`);
494
480
 
@@ -502,88 +488,98 @@ function update(resourceType, path, data, options, callback) {
502
488
  * @public
503
489
  * @function
504
490
  * @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'}`.
491
+ * @param {Object} filters - Filters to limit what resources are retrieved.
492
+ * @param {Object} [options] - Optional `options` to define URL parameters beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.
506
493
  * @param {function} [callback] - Optional callback to handle the response
507
494
  * @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',
495
+ * @example <caption>Get all data values for the 'pBOMPrpg1QX' dataset.</caption>
496
+ * get('dataValueSets', {
497
+ * dataSet: 'pBOMPrpg1QX',
498
+ * orgUnit: 'DiszpKrYNg8',
499
+ * period: '201401',
500
+ * fields: '*',
514
501
  * });
502
+ * @example <caption>get all programs for an organization unit</caption>
503
+ * get('programs', { orgUnit: 'TSyzvBiovKh', fields: '*' });
515
504
  */
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
505
 
519
506
 
520
- function get(resourceType, options, callback) {
507
+ function get(resourceType, filters, options, callback) {
521
508
  return state => {
522
509
  console.log(`Preparing get operation...`);
523
510
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
511
+ filters = (0, _languageCommon.expandReferences)(filters)(state);
524
512
  options = (0, _languageCommon.expandReferences)(options)(state);
513
+ const {
514
+ params,
515
+ requestConfig
516
+ } = options || {};
525
517
  const {
526
518
  configuration
527
519
  } = state;
528
520
  return (0, _Client.request)(configuration, {
529
521
  method: 'get',
530
522
  url: (0, _Utils.generateUrl)(configuration, options, resourceType),
531
- params: (0, _Utils.buildUrlParams)(options),
532
- responseType: 'json'
523
+ params: (0, _Utils.buildUrlParams)({ ...filters,
524
+ ...params
525
+ }),
526
+ responseType: 'json',
527
+ ...requestConfig
533
528
  }).then(result => {
534
- _Utils.Log.success(`Retrieved ${result.data[resourceType].length} ${resourceType}.`);
529
+ _Utils.Log.success(`Retrieved ${resourceType}`);
535
530
 
536
531
  return (0, _Utils.handleResponse)(result, state, callback);
537
532
  });
538
533
  };
539
- }
540
- /**
541
- * 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
- * @public
543
- * @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'}`.
547
- * @param {function} [callback] - Optional callback to handle the response
548
- * @throws {RangeError} - Throws range error
549
- * @returns {Operation}
550
- * @example <caption>Example `expression.js` of upsert</caption>
551
- * upsert(
552
- * 'trackedEntityInstances',
553
- * {
554
- * attributeId: 'lZGmxYbs97q',
555
- * attributeValue: state =>
556
- * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
557
- * .value,
558
- * },
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
566
- */
534
+ } // /**
535
+ // * 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.
536
+ // * @public
537
+ // * @function
538
+ // * @param {string} resourceType - The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`
539
+ // * @param {Object} data - The update data containing new values
540
+ // * @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'}`.
541
+ // * @param {function} [callback] - Optional callback to handle the response
542
+ // * @throws {RangeError} - Throws range error
543
+ // * @returns {Operation}
544
+ // * @example <caption>Example `expression.js` of upsert</caption>
545
+ // * upsert(
546
+ // * 'trackedEntityInstances',
547
+ // * {
548
+ // * attributeId: 'lZGmxYbs97q',
549
+ // * attributeValue: state =>
550
+ // * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
551
+ // * .value,
552
+ // * },
553
+ // * state.data,
554
+ // * { ou: 'TSyzvBiovKh' }
555
+ // * );
556
+ // */
557
+ // export function upsert(resourceType, data, options, callback) {
558
+ // return state => {
559
+ // console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
560
+ // return get(
561
+ // resourceType,
562
+ // data
563
+ // )(state).then(resp => {
564
+ // const resources = resp.data[resourceType];
565
+ // if (resources.length > 1) {
566
+ // throw new RangeError(
567
+ // `Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`
568
+ // );
569
+ // } else if (resources.length <= 0) {
570
+ // return create(resourceType, data, options, callback)(state);
571
+ // } else {
572
+ // const pathName =
573
+ // resourceType === 'trackedEntityInstances'
574
+ // ? 'trackedEntityInstance'
575
+ // : 'id';
576
+ // const path = resources[0][pathName];
577
+ // return update(resourceType, path, data, options, callback)(state);
578
+ // }
579
+ // });
580
+ // };
581
+ // }
567
582
 
568
-
569
- function upsert(resourceType, data, options, callback) {
570
- return state => {
571
- console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
572
- return get(resourceType, options)(state).then(resp => {
573
- const resources = resp.data[resourceType];
574
-
575
- if (resources.length > 1) {
576
- throw new RangeError(`Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`);
577
- } else if (resources.length <= 0) {
578
- return create(resourceType, data, options, callback)(state);
579
- } else {
580
- const pathName = resourceType === 'trackedEntityInstances' ? 'trackedEntityInstance' : 'id';
581
- const path = resources[0][pathName];
582
- return update(resourceType, path, data, options, callback)(state);
583
- }
584
- });
585
- };
586
- }
587
583
  /**
588
584
  * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
589
585
  * @public
@@ -661,6 +657,7 @@ function discover(httpMethod, endpoint) {
661
657
  * });
662
658
  */
663
659
  // TODO: @Elias, can this be deleted in favor of update? How does DHIS2 handle PATCH vs PUT?
660
+ // I need to investigate on this. But I think DHIS 2 forces to send all properties back when we do an update. If that's confirmed then this may be needed.
664
661
 
665
662
 
666
663
  function patch(resourceType, path, data, params, options, callback) {
package/lib/Client.js CHANGED
@@ -9,19 +9,35 @@ var _axios = _interopRequireDefault(require("axios"));
9
9
 
10
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
11
 
12
+ /**
13
+ * The request client takes configuration from state and an axios request object
14
+ * then (1) logs the method and URL, (2) applies standard headers and auth
15
+ * before spreading the rest of the axios configuration, and (3) executes an
16
+ * axios request.
17
+ * @function
18
+ * @param {object} configuration - configuration must have a username and password
19
+ * @param {object} axiosRequest - the axiosRequest contains valid axios params: https://axios-http.com/docs/req_config
20
+ * @returns {Promise} a promise that will resolve to either a response object or an error object.
21
+ */
12
22
  function request({
13
23
  username,
14
24
  password
15
25
  }, axiosRequest) {
16
26
  const {
17
27
  method,
18
- url
28
+ url,
29
+ params
19
30
  } = axiosRequest;
20
31
  console.log(`Sending ${method} request to ${url}`);
21
- return _axios.default.request({
32
+ if (params) console.log(` with params: ${params}`); // NOTE: We don't follow redirects for unsafe methods: https://github.com/axios/axios/issues/2460
33
+
34
+ const safeRedirect = ['get', 'head', 'options', 'trace'].includes(method.toLowerCase());
35
+ return (0, _axios.default)({
22
36
  headers: {
23
37
  'Content-Type': 'application/json'
24
38
  },
39
+ responseType: 'json',
40
+ maxRedirects: safeRedirect ? 5 : 0,
25
41
  auth: {
26
42
  username,
27
43
  password
package/lib/Utils.js CHANGED
@@ -11,14 +11,8 @@ exports.generateUrl = generateUrl;
11
11
  exports.buildUrlParams = buildUrlParams;
12
12
  exports.Log = exports.CONTENT_TYPES = void 0;
13
13
 
14
- var _axios = _interopRequireDefault(require("axios"));
15
-
16
- var _lodash = require("lodash");
17
-
18
14
  var _languageCommon = require("@openfn/language-common");
19
15
 
20
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
-
22
16
  const CONTENT_TYPES = {
23
17
  xml: 'application/xml',
24
18
  json: 'application/json',
@@ -30,15 +24,15 @@ exports.CONTENT_TYPES = CONTENT_TYPES;
30
24
 
31
25
  class Log {
32
26
  static success(message) {
33
- return console.info(`✓ ${message} @ ${new Date()}`);
27
+ return console.info(`✓ Success at ${new Date()}:\n`, message);
34
28
  }
35
29
 
36
30
  static warn(message) {
37
- return console.warn(`⚠ Warning: ${message} @ ${new Date()}`);
31
+ return console.warn(`⚠ Warning at ${new Date()}:\n`, message);
38
32
  }
39
33
 
40
34
  static error(message) {
41
- return console.error(`✗ Error: ${message} @ ${new Date()}`);
35
+ return console.error(`✗ Error at ${new Date()}:\n`, message);
42
36
  }
43
37
 
44
38
  }
@@ -48,81 +42,20 @@ exports.Log = Log;
48
42
  function buildUrl(path, hostUrl, apiVersion) {
49
43
  const pathSuffix = apiVersion ? `/${apiVersion}${path}` : `${path}`;
50
44
  return hostUrl + '/api' + pathSuffix;
51
- }
45
+ } // Write a unit test for this one
46
+
52
47
 
53
48
  function handleResponse(result, state, callback) {
54
- // TODO: @Elias, should composeNextState get passed result OR result.data?
55
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
56
- return (0, _languageCommon.composeNextState)(state, result.data);
49
+ const {
50
+ data
51
+ } = result;
52
+ if (callback) return callback((0, _languageCommon.composeNextState)(state, data));
53
+ return (0, _languageCommon.composeNextState)(state, data);
57
54
  }
58
55
 
59
56
  function prettyJson(data) {
60
57
  return JSON.stringify(data, null, 2);
61
- } // =============================================================================
62
- // TODO: @Elias... what are these functions doing and do they have a place in the new implementation?
63
- // export function getIndicesOf(string, regex) {
64
- // var match,
65
- // indexes = {};
66
- // regex = new RegExp(regex);
67
- // while ((match = regex.exec(string))) {
68
- // let schemaRef;
69
- // if (!indexes[match[0]]) {
70
- // indexes[match[0]] = {};
71
- // }
72
- // let hrefString = string.slice(
73
- // match.index,
74
- // indexOf(string, '}', match.index) - 1
75
- // );
76
- // let lastIndex = lastIndexOf(hrefString, '/') + 1;
77
- // schemaRef = trim(hrefString.slice(lastIndex));
78
- // indexes[match[0]][match.index] = schemaRef;
79
- // }
80
- // return indexes;
81
- // }
82
- // export function isLike(string, words) {
83
- // const wordsArrary = words?.match(/([^\W]+[^\s,]*)/)?.splice(0, 1);
84
- // const isFound = word => RegExp(word, 'i')?.test(string);
85
- // return some(wordsArrary, isFound);
86
- // }
87
- // export const dhis2OperatorMap = {
88
- // eq: eq,
89
- // like: isLike,
90
- // };
91
- // export function applyFilter(
92
- // arrObject,
93
- // targetProperty,
94
- // operator,
95
- // valueToCompareWith
96
- // ) {
97
- // if (targetProperty && operator && valueToCompareWith) {
98
- // try {
99
- // return filter(arrObject, obj =>
100
- // Reflect.apply(operator, obj, [obj[targetProperty], valueToCompareWith])
101
- // );
102
- // } catch (error) {
103
- // Log.warn(
104
- // `Returned unfiltered data. Failed to apply custom filter(${prettyJson({
105
- // targetProperty: targetProperty ?? null,
106
- // operator: operator ?? null,
107
- // value: valueToCompareWith ?? null,
108
- // })}) on this collection. The operator you supplied maybe unsupported on this resource at the moment.`
109
- // );
110
- // return arrObject;
111
- // }
112
- // }
113
- // console.log('No filters applied; returned all records for this resource.');
114
- // return arrObject;
115
- // }
116
- // export function parseFilter(filterExpression) {
117
- // const filterTokens = filterExpression?.split(':');
118
- // filterTokens
119
- // ? (filterTokens[1] = dhis2OperatorMap[filterTokens[1] ?? null])
120
- // : null;
121
- // return filterTokens;
122
- // }
123
- // // TODO: @Elias, end of the investigation block!
124
- // =============================================================================
125
-
58
+ }
126
59
 
127
60
  const isArray = variable => !!variable && variable.constructor === Array;
128
61
 
@@ -139,22 +72,19 @@ function generateUrl(configuration, options, resourceType) {
139
72
  } = configuration;
140
73
  const urlString = '/' + resourceType; // Note that users can override the apiVersion from configuration with args
141
74
 
142
- if (options === null || options === void 0 ? void 0 : options.apiVersion) apiVersion = options.apiVersion; // TODO: discuss how this actually works on DHIS2. I'm not sure I'm following.
143
-
75
+ if (options === null || options === void 0 ? void 0 : options.apiVersion) apiVersion = options.apiVersion;
144
76
  const apiMessage = apiVersion ? `Using DHIS2 api version ${apiVersion}` : 'Using latest available version of the DHIS2 api on this server.';
145
77
  console.log(apiMessage);
146
78
  return buildUrl(urlString, hostUrl, apiVersion);
147
79
  }
148
80
 
149
- function buildUrlParams(options) {
150
- var _options$params, _options$params2, _options$params3, _options$params4;
151
-
152
- const filters = options === null || options === void 0 ? void 0 : (_options$params = options.params) === null || _options$params === void 0 ? void 0 : _options$params.filters;
153
- const dimensions = options === null || options === void 0 ? void 0 : (_options$params2 = options.params) === null || _options$params2 === void 0 ? void 0 : _options$params2.dimensions; // We remove filters and dimensions before building standard search params.
81
+ function buildUrlParams(params) {
82
+ const filters = params === null || params === void 0 ? void 0 : params.filters;
83
+ const dimensions = params === null || params === void 0 ? void 0 : params.dimensions; // We remove filters and dimensions before building standard search params.
154
84
 
155
- options === null || options === void 0 ? true : (_options$params3 = options.params) === null || _options$params3 === void 0 ? true : delete _options$params3.filters;
156
- options === null || options === void 0 ? true : (_options$params4 = options.params) === null || _options$params4 === void 0 ? true : delete _options$params4.dimensions;
157
- const urlParams = new URLSearchParams(options === null || options === void 0 ? void 0 : options.params); // Then we re-apply the filters and dimensions in this dhis2-specific way.
85
+ params === null || params === void 0 ? true : delete params.filters;
86
+ params === null || params === void 0 ? true : delete params.dimensions;
87
+ const urlParams = new URLSearchParams(params); // Then we re-apply the filters and dimensions in this dhis2-specific way.
158
88
 
159
89
  filters === null || filters === void 0 ? void 0 : filters.map(f => urlParams.append('filter', f));
160
90
  dimensions === null || dimensions === void 0 ? void 0 : dimensions.map(d => urlParams.append('dimension', d));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-dhis2",
3
- "version": "3.0.0-0",
3
+ "version": "3.0.0-2",
4
4
  "description": "DHIS2 Language Pack for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {