@openfn/language-dhis2 3.0.0-4 → 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/README.md CHANGED
@@ -1,13 +1,28 @@
1
- # Language DHIS2 [![Build Status](https://travis-ci.org/OpenFn/language-dhis2.svg?branch=main)](https://travis-ci.org/OpenFn/language-dhis2)
1
+ # Language DHIS2 [<img src="https://avatars2.githubusercontent.com/u/9555108?s=200&v=4)" alt="alt text" height="20">](https://www.openfn.org) [![CircleCI](https://circleci.com/gh/OpenFn/language-dhis2.svg?style=svg)](https://circleci.com/gh/OpenFn/language-dhis2)
2
2
 
3
- Language Pack for building expressions and operations for working with the
3
+ An OpenFn language Pack for building expressions and operations for working with
4
+ the
4
5
  [DHIS2 API](http://dhis2.github.io/dhis2-docs/master/en/developer/html/dhis2_developer_manual.html).
6
+ Used most commonly via OpenFn.org or by hand with
7
+ [OpenFn/core](https://github.com/OpenFn/core) from the root of this repo:
8
+
9
+ ```sh
10
+ core execute \
11
+ -l ../language-dhis2 \
12
+ -e ./tmp/myExpressions.js \
13
+ -s ./tmp/state.json \
14
+ -o ./tmp/output.json
15
+ ```
5
16
 
6
17
  ## Documentation
7
18
 
8
19
  View the [docs site](https://openfn.github.io/language-dhis2/) for full
9
- technical documentation. Below, find a samples of the most commonly used helper
10
- functions.
20
+ technical documentation.
21
+
22
+ There are lots of **examples** for how to use the various helper functions on
23
+ the main
24
+ [Adaptor docs](https://openfn.github.io/language-dhis2/module-Adaptor.html)
25
+ page.
11
26
 
12
27
  ## Sample State
13
28
 
@@ -16,165 +31,25 @@ functions.
16
31
  "configuration": {
17
32
  "username": "admin",
18
33
  "password": "district",
19
- "hostUrl": "https://play.dhis2.org/2.35.1"
34
+ "hostUrl": "https://play.dhis2.org/2.36.6"
20
35
  },
21
- "data": {
22
- "a": 1,
23
- "b": 2
24
- }
36
+ "data": { "a": 1, "b": 2 }
25
37
  }
26
38
  ```
27
39
 
28
- ## Analytics API
29
-
30
- #### Fetch analytics data for PMTCT data over last 6 months.
31
-
32
- ```js
33
- fetchAnalytics({
34
- query: {
35
- dimension: ['dx:CYI5LEmm3cG;GDVU1o5rTNF', 'pe:LAST_6_MONTHS'],
36
- filter: 'ou:GHlyx9Pg9mn',
37
- displayProperty: 'NAME',
38
- outputIdScheme: 'UID',
39
- },
40
- });
41
- ```
42
-
43
- ## Tracked Entity API
44
-
45
- #### Create a new tracked entity instance and enroll them from a CommCare form submission.
46
-
47
- ```js
48
- createTEI({
49
- trackedEntityType: 'nEenWmSyUEp',
50
- orgUnit: 'g8upMTyEZGZ',
51
- attributes: [
52
- {
53
- attribute: 'w75KJ2mc4zz',
54
- value: dataValue('form.first_name')(state),
55
- },
56
- {
57
- attribute: 'zDhUuAYrxNC',
58
- value: dataValue('form.last_name')(state),
59
- },
60
- ],
61
- enrollments: [
62
- {
63
- orgUnit: 'g8upMTyEZGZ',
64
- program: 'IpHINAT79UW',
65
- enrollmentDate: '2019-04-08',
66
- incidentDate: '2019-04-08',
67
- },
68
- ],
69
- });
70
- ```
71
-
72
- #### Upsert a tracked entity instance from a CommCare form submission.
73
-
74
- ```js
75
- upsertTEI(
76
- 'w75KJ2mc4zz', // match on 'patientID', a custom external ID in dhis2
77
- {
78
- trackedEntityType: 'nEenWmSyUEp',
79
- orgUnit: 'g8upMTyEZGZ',
80
- attributes: [
81
- {
82
- attribute: 'w75KJ2mc4zz',
83
- value: dataValue('form.first_name')(state),
84
- },
85
- {
86
- attribute: 'zDhUuAYrxNC',
87
- value: dataValue('form.last_name')(state),
88
- },
89
- ],
90
- }
91
- );
92
- ```
93
-
94
- ## Events API
95
-
96
- #### `Events API` expression
97
-
98
- ```js
99
- event(
100
- fields(
101
- field("program", "eBAyeGv0exc"),
102
- field("orgUnit", "DiszpKrYNg8"),
103
- field("eventDate", dataValue("date")),
104
- field("status", "COMPLETED"),
105
- field("storedBy", "admin"),
106
- field("coordinate", {
107
- "latitude": "59.8",
108
- "longitude": "10.9"
109
- }),
110
- field("dataValues", function(state) {
111
- return [
112
- dataElement("qrur9Dvnyt5", dataValue("prop_a"))(state)
113
- dataElement("oZg33kd9taw", dataValue("prop_b"))(state)
114
- dataElement("msodh3rEMJa", dataValue("prop_c"))(state)
115
- ]
116
- })
117
- )
118
- )
119
- ```
120
-
121
- #### Current `fetchEvents API` expression (Optional `postUrl` for a complete fetch)
122
-
123
- ```js
124
- fetchEvents({
125
- fields: {
126
- orgUnit: 'DiszpKrYNg8',
127
- program: 'eBAyeGv0exc',
128
- endDate: '2016-01-01',
129
- },
130
- postUrl: 'https://www.openfn.org/inbox/123',
131
- });
132
- ```
133
-
134
- #### Reference on how to query and read events https://docs.dhis2.org/2.22/en/developer/html/ch01s15.html#d5e1994
135
-
136
- ## Data Values / Data Value Sets API
137
-
138
- #### Current `DataValueSets API` expression
139
-
140
- ```js
141
- dataValueSet({
142
- dataSet: dataValue('set'),
143
- orgUnit: 'DiszpKrYNg8',
144
- period: '201402',
145
- completeData: '2014-03-03',
146
- dataValues: [
147
- dataElement('f7n9E0hX8qk', dataValue('data[0].site_school_number')),
148
- dataElement('Ix2HsbDMLea', dataValue('age')),
149
- dataElement('eY5ehpbEsB7', 30),
150
- ],
151
- });
152
- ```
153
-
154
- #### Current `fetchData API` expression (Optional `postUrl` for a complete fetch)
155
-
156
- ```js
157
- fetchData({
158
- fields: {
159
- dataSet: 'pBOMPrpg1QX',
160
- orgUnit: 'DiszpKrYNg8',
161
- period: '201711',
162
- },
163
- postUrl: 'https://www.openfn.org/inbox/123',
164
- });
165
- ```
166
-
167
- #### Reference on how to read data values https://docs.dhis2.org/2.22/en/developer/html/ch01s13.html#d5e1642
168
-
169
- [Docs](docs/index)
170
-
171
40
  ## Development
172
41
 
173
- Clone the repo, run `npm install`.
42
+ Clone the repo and run `npm install`.
43
+
44
+ Run tests using `npm run test` or `npm run test:watch`. (NB: that this repo also
45
+ contain integration tests which can be run with `npm run integration-test`.)
174
46
 
175
- Run tests using `npm run test` or `npm run test:watch`
47
+ ⚠️ NB: Make changes to the files in `src/` and then use `npm run build` to
48
+ generate output files in `lib/`.
176
49
 
177
- NB: There are two types of tests: unit tests and integration tests.
50
+ The documentation is autogenerated, so please **rebuild the docs** after making
51
+ changes by running
52
+ `./node_modules/.bin/jsdoc --readme ./README.md ./lib -d docs`
178
53
 
179
54
  ### Unit Tests
180
55
 
@@ -191,22 +66,56 @@ needs to be added.
191
66
 
192
67
  ### End-to-end integration tests
193
68
 
194
- Integration tests allow us to test the end-to-end behavior of the helper functions
195
- and also to test the examples we provide via inline documentation.
69
+ Integration tests allow us to test the end-to-end behavior of the helper
70
+ functions and also to test the examples we provide via inline documentation.
196
71
 
197
72
  For example with integration tests we answer the following question:
198
73
 
199
74
  > Does `create('events', eventPayload)` actually create a new event in a live
200
75
  > DHIS2 system?
201
76
 
202
- To run integration tests, execute `npm run integration-test`. These
203
- tests use network I/O and a public connection to a DHIS2 "play" server so their
204
- timing and performance is unpredictable. Consider adding an increased timeout,
205
- and modifying the orgUnit, program, etc., IDs set in `globalState`.
206
-
207
- Anytime a new example is added in the documentation of a helper function, a new
208
- integration test should be done.
77
+ To run integration tests, execute `npm run integration-test`. These tests use
78
+ network I/O and a public connection to a DHIS2 "play" server so their timing and
79
+ performance is unpredictable. Consider adding an increased timeout, and
80
+ modifying the orgUnit, program, etc., IDs set in `globalState`.
81
+
82
+ #### Troubleshooting the tests
83
+
84
+ - Depending on your internet strength please consider changing the **global
85
+ timeout** in the `test/mocha.opts` file to avoid faillures related to network
86
+ timeouts.
87
+
88
+ - The behavior of the tests in `test/integration.js` is very unpredictable; they
89
+ depend on the **configuration of a target DHIS2 instance**. Currently you need
90
+ to have at least one organisation unit with one program, one
91
+ trackedEntityInstance and one programStage in it. These components need to be
92
+ well configured for the integration tests to work. For example: the
93
+ trackedEntityInstance need to be enrolled to the program, which should be
94
+ created in that organisation unit and contains at least that programStage. If
95
+ the tests fail, you must adjust these attributes in the
96
+ [before hook](test/integration.js):
97
+
98
+ ```javascript
99
+ before(done => {
100
+ fixture.initialState = {
101
+ configuration: {
102
+ username: 'admin',
103
+ password: 'district',
104
+ hostUrl: 'https://play.dhis2.org/2.36.6',
105
+ },
106
+ program: 'IpHINAT79UW',
107
+ orgUnit: 'DiszpKrYNg8',
108
+ trackedEntityInstance: 'uhubxsfLanV',
109
+ programStage: 'eaDHS084uMp',
110
+ };
111
+ done();
112
+ });
113
+ ```
209
114
 
210
- ### Build
115
+ - Make sure the `update` and `upsert` integration tests don't affect those
116
+ initial organisation units, programs, programStage and trackedEntityInstance
117
+ required. Otherwise the create integration tests would be broken again; and
118
+ that's an endless faillure loop :(
211
119
 
212
- Build the project using `npm run build`.
120
+ Anytime a new example is added in the documentation of a helper function, a new
121
+ integration test should be built.
package/ast.json CHANGED
@@ -360,6 +360,129 @@
360
360
  },
361
361
  "valid": true
362
362
  },
363
+ {
364
+ "name": "upsert",
365
+ "params": [
366
+ "resourceType",
367
+ "query",
368
+ "data",
369
+ "options",
370
+ "callback"
371
+ ],
372
+ "docs": {
373
+ "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.",
374
+ "tags": [
375
+ {
376
+ "title": "public",
377
+ "description": null,
378
+ "type": null
379
+ },
380
+ {
381
+ "title": "function",
382
+ "description": null,
383
+ "name": null
384
+ },
385
+ {
386
+ "title": "param",
387
+ "description": "The type of a resource to `upsert`. E.g. `trackedEntityInstances`",
388
+ "type": {
389
+ "type": "NameExpression",
390
+ "name": "string"
391
+ },
392
+ "name": "resourceType"
393
+ },
394
+ {
395
+ "title": "param",
396
+ "description": "A query object that allows to uniquely identify the resource to update. If no matches found, then the resource will be created.",
397
+ "type": {
398
+ "type": "NameExpression",
399
+ "name": "Object"
400
+ },
401
+ "name": "query"
402
+ },
403
+ {
404
+ "title": "param",
405
+ "description": "The data to use for update or create depending on the result of the query.",
406
+ "type": {
407
+ "type": "NameExpression",
408
+ "name": "Object"
409
+ },
410
+ "name": "data"
411
+ },
412
+ {
413
+ "title": "param",
414
+ "description": "Optional configuration that will be applied to both the `get` and the `create` or `update` operations.",
415
+ "type": {
416
+ "type": "OptionalType",
417
+ "expression": {
418
+ "type": "RecordType",
419
+ "fields": [
420
+ {
421
+ "type": "FieldType",
422
+ "key": "apiVersion",
423
+ "value": {
424
+ "type": "NameExpression",
425
+ "name": "object"
426
+ }
427
+ },
428
+ {
429
+ "type": "FieldType",
430
+ "key": "requestConfig",
431
+ "value": {
432
+ "type": "NameExpression",
433
+ "name": "object"
434
+ }
435
+ },
436
+ {
437
+ "type": "FieldType",
438
+ "key": "params",
439
+ "value": {
440
+ "type": "NameExpression",
441
+ "name": "object"
442
+ }
443
+ }
444
+ ]
445
+ }
446
+ },
447
+ "name": "options"
448
+ },
449
+ {
450
+ "title": "param",
451
+ "description": "Optional callback to handle the response",
452
+ "type": {
453
+ "type": "OptionalType",
454
+ "expression": {
455
+ "type": "NameExpression",
456
+ "name": "function"
457
+ }
458
+ },
459
+ "name": "callback"
460
+ },
461
+ {
462
+ "title": "throws",
463
+ "description": "Throws range error",
464
+ "type": {
465
+ "type": "NameExpression",
466
+ "name": "RangeError"
467
+ }
468
+ },
469
+ {
470
+ "title": "returns",
471
+ "description": null,
472
+ "type": {
473
+ "type": "NameExpression",
474
+ "name": "Operation"
475
+ }
476
+ },
477
+ {
478
+ "title": "example",
479
+ "description": "upsert('trackedEntityInstances', {\n ou: 'TSyzvBiovKh',\n filter: ['w75KJ2mc4zz:Eq:Qassim'],\n}, {\n orgUnit: 'TSyzvBiovKh',\n trackedEntityType: 'nEenWmSyUEp',\n attributes: [\n {\n attribute: 'w75KJ2mc4zz',\n value: 'Qassim',\n },\n ],\n});",
480
+ "caption": "Example `expression.js` of upsert"
481
+ }
482
+ ]
483
+ },
484
+ "valid": true
485
+ },
363
486
  {
364
487
  "name": "discover",
365
488
  "params": [
package/lib/Adaptor.js CHANGED
@@ -7,6 +7,7 @@ exports.execute = execute;
7
7
  exports.create = create;
8
8
  exports.update = update;
9
9
  exports.get = get;
10
+ exports.upsert = upsert;
10
11
  exports.discover = discover;
11
12
  exports.patch = patch;
12
13
  exports.destroy = destroy;
@@ -537,55 +538,64 @@ function get(resourceType, query, options = {}, callback = false) {
537
538
  return (0, _Utils.handleResponse)(result, state, callback);
538
539
  });
539
540
  };
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
- // */
563
- // export function upsert(resourceType, data, options = {}, callback = false) {
564
- // return state => {
565
- // console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
566
- // return get(
567
- // resourceType,
568
- // data
569
- // )(state).then(resp => {
570
- // const resources = resp.data[resourceType];
571
- // if (resources.length > 1) {
572
- // throw new RangeError(
573
- // `Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`
574
- // );
575
- // } else if (resources.length <= 0) {
576
- // return create(resourceType, data, options, callback)(state);
577
- // } else {
578
- // const pathName =
579
- // resourceType === 'trackedEntityInstances'
580
- // ? 'trackedEntityInstance'
581
- // : 'id';
582
- // const path = resources[0][pathName];
583
- // return update(resourceType, path, data, options, callback)(state);
584
- // }
585
- // });
586
- // };
587
- // }
541
+ }
542
+ /**
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.
544
+ * @public
545
+ * @function
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.
550
+ * @param {function} [callback] - Optional callback to handle the response
551
+ * @throws {RangeError} - Throws range error
552
+ * @returns {Operation}
553
+ * @example <caption>Example `expression.js` of upsert</caption>
554
+ * upsert('trackedEntityInstances', {
555
+ * ou: 'TSyzvBiovKh',
556
+ * filter: ['w75KJ2mc4zz:Eq:Qassim'],
557
+ * }, {
558
+ * orgUnit: 'TSyzvBiovKh',
559
+ * trackedEntityType: 'nEenWmSyUEp',
560
+ * attributes: [
561
+ * {
562
+ * attribute: 'w75KJ2mc4zz',
563
+ * value: 'Qassim',
564
+ * },
565
+ * ],
566
+ * });
567
+ */
588
568
 
569
+
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
+ ) {
576
+ return state => {
577
+ console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
578
+ return get(resourceType, query, options)(state).then(resp => {
579
+ const resources = resp.data[resourceType];
580
+
581
+ if (resources.length > 1) {
582
+ throw new RangeError(`Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`);
583
+ } else if (resources.length <= 0) {
584
+ return create(resourceType, data, options)(state);
585
+ } else {
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);
591
+ }
592
+ }).then(result => {
593
+ _Utils.Log.success(`Performed a "composed upsert" on ${resourceType}`);
594
+
595
+ return (0, _Utils.handleResponse)(result, state, callback);
596
+ });
597
+ };
598
+ }
589
599
  /**
590
600
  * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
591
601
  * @public
@@ -659,7 +669,7 @@ function discover(httpMethod, endpoint) {
659
669
  * patch('dataElements', 'FTRrcoaog83', { name: 'New Name' });
660
670
  */
661
671
  // TODO: @Elias, can this be deleted in favor of update? How does DHIS2 handle PATCH vs PUT?
662
- // 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.
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.
663
673
 
664
674
 
665
675
  function patch(resourceType, path, data, options = {}, callback = false) {
package/lib/Utils.js CHANGED
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.buildUrl = buildUrl;
7
+ exports.selectId = selectId;
7
8
  exports.handleResponse = handleResponse;
8
9
  exports.prettyJson = prettyJson;
9
10
  exports.nestArray = nestArray;
@@ -38,9 +39,28 @@ class Log {
38
39
 
39
40
  exports.Log = Log;
40
41
 
41
- function buildUrl(path, hostUrl, apiVersion) {
42
- const pathSuffix = apiVersion ? `/${apiVersion}${path}` : `${path}`;
42
+ function buildUrl(urlString, hostUrl, apiVersion) {
43
+ const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
43
44
  return hostUrl + '/api' + pathSuffix;
45
+ }
46
+ /**
47
+ * Determines the attribute name for a DHIS2 system ID given a resource type.
48
+ * @param {string} resourceType
49
+ * @returns {string}
50
+ */
51
+
52
+
53
+ function selectId(resourceType) {
54
+ switch (resourceType) {
55
+ case 'trackedEntityInstances':
56
+ return 'trackedEntityInstance';
57
+ // We can extend here if we find other special kinds of resourceType
58
+ // case 'other-special-case':
59
+ // return 'other-special-id';
60
+
61
+ default:
62
+ return 'id';
63
+ }
44
64
  } // Write a unit test for this one
45
65
 
46
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-dhis2",
3
- "version": "3.0.0-4",
3
+ "version": "3.0.0",
4
4
  "description": "DHIS2 Language Pack for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {