@openfn/language-dhis2 2.0.8 → 3.0.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.
Files changed (44) hide show
  1. package/README.md +39 -4
  2. package/ast.json +295 -2430
  3. package/lib/Adaptor.js +475 -1519
  4. package/lib/Client.js +32 -0
  5. package/lib/Utils.js +124 -175
  6. package/lib/index.js +4 -6
  7. package/node_modules/@openfn/language-common/node_modules/axios/package.json +20 -0
  8. package/node_modules/@openfn/language-common/node_modules/follow-redirects/package.json +20 -0
  9. package/node_modules/@openfn/language-common/node_modules/jsonpath-plus/package.json +20 -0
  10. package/node_modules/@openfn/language-common/node_modules/lodash/package.json +20 -0
  11. package/node_modules/@openfn/language-common/package.json +8 -4
  12. package/node_modules/axios/CHANGELOG.md +159 -8
  13. package/node_modules/axios/README.md +98 -6
  14. package/node_modules/axios/SECURITY.md +5 -0
  15. package/node_modules/axios/dist/axios.js +2101 -1582
  16. package/node_modules/axios/dist/axios.map +1 -1
  17. package/node_modules/axios/dist/axios.min.js +1 -2
  18. package/node_modules/axios/dist/axios.min.map +1 -1
  19. package/node_modules/axios/index.d.ts +76 -31
  20. package/node_modules/axios/lib/adapters/http.js +74 -14
  21. package/node_modules/axios/lib/adapters/xhr.js +66 -33
  22. package/node_modules/axios/lib/axios.js +6 -5
  23. package/node_modules/axios/lib/cancel/CancelToken.js +62 -0
  24. package/node_modules/axios/lib/core/Axios.js +60 -7
  25. package/node_modules/axios/lib/core/InterceptorManager.js +4 -2
  26. package/node_modules/axios/lib/core/README.md +1 -0
  27. package/node_modules/axios/lib/core/dispatchRequest.js +11 -3
  28. package/node_modules/axios/lib/core/enhanceError.js +2 -1
  29. package/node_modules/axios/lib/core/mergeConfig.js +50 -38
  30. package/node_modules/axios/lib/core/transformData.js +3 -1
  31. package/node_modules/axios/lib/defaults.js +48 -12
  32. package/node_modules/axios/lib/env/README.md +3 -0
  33. package/node_modules/axios/lib/env/data.js +3 -0
  34. package/node_modules/axios/lib/helpers/validator.js +82 -0
  35. package/node_modules/axios/lib/utils.js +1 -3
  36. package/node_modules/axios/package.json +37 -40
  37. package/node_modules/axios/tsconfig.json +14 -0
  38. package/node_modules/axios/tslint.json +6 -0
  39. package/node_modules/follow-redirects/README.md +1 -1
  40. package/node_modules/follow-redirects/debug.js +14 -8
  41. package/node_modules/follow-redirects/index.js +106 -41
  42. package/node_modules/follow-redirects/package.json +14 -17
  43. package/node_modules/lodash/package.json +2 -2
  44. package/package.json +5 -4
package/lib/Adaptor.js CHANGED
@@ -4,108 +4,81 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.execute = execute;
7
- exports.getTEIs = getTEIs;
8
- exports.upsertTEI = upsertTEI;
9
- exports.createTEI = createTEI;
10
- exports.updateTEI = updateTEI;
11
- exports.getEvents = getEvents;
12
- exports.createEvents = createEvents;
13
- exports.updateEvents = updateEvents;
14
- exports.getPrograms = getPrograms;
15
- exports.createPrograms = createPrograms;
16
- exports.updatePrograms = updatePrograms;
17
- exports.getEnrollments = getEnrollments;
18
- exports.enrollTEI = enrollTEI;
19
- exports.updateEnrollments = updateEnrollments;
20
- exports.cancelEnrollment = cancelEnrollment;
21
- exports.completeEnrollment = completeEnrollment;
22
- exports.getRelationships = getRelationships;
23
- exports.getDataValues = getDataValues;
24
- exports.createDataValues = createDataValues;
25
- exports.generateDhis2UID = generateDhis2UID;
26
- exports.discover = discover;
27
- exports.getAnalytics = getAnalytics;
28
- exports.getResources = getResources;
29
- exports.getSchema = getSchema;
30
- exports.getData = getData;
31
- exports.getMetadata = getMetadata;
32
7
  exports.create = create;
33
8
  exports.update = update;
9
+ exports.get = get;
10
+ exports.upsert = upsert;
11
+ exports.discover = discover;
34
12
  exports.patch = patch;
35
13
  exports.del = del;
36
- exports.upsert = upsert;
14
+ exports.attrVal = attrVal;
15
+ exports.attribute = attribute;
37
16
  Object.defineProperty(exports, "field", {
38
17
  enumerable: true,
39
- get: function get() {
18
+ get: function () {
40
19
  return _languageCommon.field;
41
20
  }
42
21
  });
43
22
  Object.defineProperty(exports, "fields", {
44
23
  enumerable: true,
45
- get: function get() {
24
+ get: function () {
46
25
  return _languageCommon.fields;
47
26
  }
48
27
  });
49
28
  Object.defineProperty(exports, "sourceValue", {
50
29
  enumerable: true,
51
- get: function get() {
30
+ get: function () {
52
31
  return _languageCommon.sourceValue;
53
32
  }
54
33
  });
55
34
  Object.defineProperty(exports, "merge", {
56
35
  enumerable: true,
57
- get: function get() {
36
+ get: function () {
58
37
  return _languageCommon.merge;
59
38
  }
60
39
  });
61
40
  Object.defineProperty(exports, "each", {
62
41
  enumerable: true,
63
- get: function get() {
42
+ get: function () {
64
43
  return _languageCommon.each;
65
44
  }
66
45
  });
67
46
  Object.defineProperty(exports, "dataPath", {
68
47
  enumerable: true,
69
- get: function get() {
48
+ get: function () {
70
49
  return _languageCommon.dataPath;
71
50
  }
72
51
  });
73
52
  Object.defineProperty(exports, "dataValue", {
74
53
  enumerable: true,
75
- get: function get() {
54
+ get: function () {
76
55
  return _languageCommon.dataValue;
77
56
  }
78
57
  });
79
58
  Object.defineProperty(exports, "lastReferenceValue", {
80
59
  enumerable: true,
81
- get: function get() {
60
+ get: function () {
82
61
  return _languageCommon.lastReferenceValue;
83
62
  }
84
63
  });
85
64
  Object.defineProperty(exports, "alterState", {
86
65
  enumerable: true,
87
- get: function get() {
66
+ get: function () {
88
67
  return _languageCommon.alterState;
89
68
  }
90
69
  });
91
70
  Object.defineProperty(exports, "fn", {
92
71
  enumerable: true,
93
- get: function get() {
72
+ get: function () {
94
73
  return _languageCommon.fn;
95
74
  }
96
75
  });
97
76
  Object.defineProperty(exports, "http", {
98
77
  enumerable: true,
99
- get: function get() {
78
+ get: function () {
100
79
  return _languageCommon.http;
101
80
  }
102
81
  });
103
- Object.defineProperty(exports, "attribute", {
104
- enumerable: true,
105
- get: function get() {
106
- return _Utils.attribute;
107
- }
108
- });
109
82
 
110
83
  var _axios = _interopRequireDefault(require("axios"));
111
84
 
@@ -115,33 +88,11 @@ var _lodash = require("lodash");
115
88
 
116
89
  var _Utils = require("./Utils");
117
90
 
118
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
119
-
120
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
121
-
122
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
123
-
124
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
125
-
126
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
127
-
128
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
129
-
130
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
131
-
132
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
133
-
134
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
135
-
136
- function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
91
+ var _Client = require("./Client");
137
92
 
138
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
93
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
139
94
 
140
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
141
-
142
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
143
-
144
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
95
+ /** @module Adaptor */
145
96
 
146
97
  /**
147
98
  * Execute a sequence of operations.
@@ -155,17 +106,15 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope
155
106
  * @param {Operations} operations - Operations to be performed.
156
107
  * @returns {Operation}
157
108
  */
158
- function execute() {
159
- for (var _len = arguments.length, operations = new Array(_len), _key = 0; _key < _len; _key++) {
160
- operations[_key] = arguments[_key];
161
- }
162
-
163
- var initialState = {
109
+ function execute(...operations) {
110
+ const initialState = {
164
111
  references: [],
165
112
  data: null
166
113
  };
167
- return function (state) {
168
- return _languageCommon.execute.apply(void 0, [configMigrationHelper].concat(operations))(_objectSpread({}, initialState, {}, state));
114
+ return state => {
115
+ return (0, _languageCommon.execute)(configMigrationHelper, ...operations)({ ...initialState,
116
+ ...state
117
+ });
169
118
  };
170
119
  }
171
120
  /**
@@ -180,9 +129,10 @@ function execute() {
180
129
 
181
130
 
182
131
  function configMigrationHelper(state) {
183
- var _state$configuration = state.configuration,
184
- hostUrl = _state$configuration.hostUrl,
185
- apiUrl = _state$configuration.apiUrl;
132
+ const {
133
+ hostUrl,
134
+ apiUrl
135
+ } = state.configuration;
186
136
 
187
137
  if (!hostUrl) {
188
138
  _Utils.Log.warn('DEPRECATION WARNING: Please migrate instance address from `apiUrl` to `hostUrl`.');
@@ -192,19 +142,21 @@ function configMigrationHelper(state) {
192
142
  }
193
143
 
194
144
  return state;
195
- }
145
+ } // NOTE: In order to prevent unintended exposure of authentication information
146
+ // in the logs, we make use of an axios interceptor.
196
147
 
197
- _axios["default"].interceptors.response.use(function (response) {
148
+
149
+ _axios.default.interceptors.response.use(function (response) {
198
150
  var _response$headers$con, _response;
199
151
 
200
- var contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
201
- var acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');
152
+ const contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
153
+ const acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');
202
154
 
203
155
  if (response.config.method === 'get') {
204
156
  if ((0, _lodash.indexOf)(acceptHeaders, contentType) === -1) {
205
- var newError = {
157
+ const newError = {
206
158
  status: 404,
207
- message: 'Unexpected content,returned',
159
+ message: 'Unexpected content returned',
208
160
  responseData: response.data
209
161
  };
210
162
 
@@ -216,778 +168,424 @@ _axios["default"].interceptors.response.use(function (response) {
216
168
 
217
169
  if (typeof ((_response = response) === null || _response === void 0 ? void 0 : _response.data) === 'string' && contentType === (_Utils.CONTENT_TYPES === null || _Utils.CONTENT_TYPES === void 0 ? void 0 : _Utils.CONTENT_TYPES.json)) {
218
170
  try {
219
- response = _objectSpread({}, response, {
171
+ response = { ...response,
220
172
  data: JSON.parse(response.data)
221
- });
173
+ };
222
174
  } catch (error) {
223
- /* Keep quiet */
175
+ _Utils.Log.warn('Non-JSON response detected, unable to parse.');
224
176
  }
225
177
  }
226
178
 
227
179
  return response;
228
180
  }, function (error) {
229
- _Utils.Log.error("".concat(error === null || error === void 0 ? void 0 : error.message));
181
+ try {
182
+ var _details$config, _details$config2;
230
183
 
231
- return Promise.reject(JSON.stringify(error.response.data, null, 2));
232
- });
233
- /**
234
- * Get Tracked Entity Instance(s).
235
- * @public
236
- * @function
237
- * @param {Object} [params] - Optional `query parameters` e.g. `{ou: 'DiszpKrYNg8', filters: ['lZGmxYbs97q':GT:5']}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html DHIS2 docs} for more details on which params to use when querying tracked entities instances.
238
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getTEIs` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
239
- * @param {function} [callback] - Optional callback to handle the response.
240
- * @returns {Operation}
241
- * @example <caption>- Example `getTEIs` `expression.js` for fetching a `single` `Tracked Entity Instance` with all the fields included.</caption>
242
- * getTEIs({
243
- * fields: '*',
244
- * ou: 'CMqUILyVnBL',
245
- * trackedEntityInstance: 'HNTA9qD6EEG',
246
- * skipPaging: true,
247
- * });
248
- */
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--';
249
187
 
188
+ _Utils.Log.error(details.message);
250
189
 
251
- function getTEIs(params, options, callback) {
252
- return function (state) {
253
- options = (0, _languageCommon.expandReferences)(options)(state);
254
- if (options) options.operationName = 'getTEIs';else {
255
- options = {
256
- operationName: 'getTEIs'
257
- };
258
- }
259
- return getData('trackedEntityInstances', params, options, callback)(state);
260
- };
261
- }
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
+ }
198
+ });
262
199
  /**
263
- * Update TEI if exists otherwise create.
264
- * - Update if the record exists otherwise insert a new record.
265
- * - This is useful for idempotency and duplicate record management.
200
+ * Create a record
266
201
  * @public
267
202
  * @function
268
- * @param {string} uniqueAttributeId - Tracked Entity Instance unique identifier attribute used during matching.
269
- * @param {Object} data - Payload data for new tracked entity instance or updated data for an existing tracked entity instance.
270
- * @param {{apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
271
- * @param {function} [callback] - Optional `callback` to handle the response.
272
- * @throws {RangeError} - Throws `RangeError` when `uniqueAttributeId` is `invalid` or `not unique`.
203
+ * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`, `programs`, `events`, ...
204
+ * @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'}`
206
+ * @param {function} [callback] - Optional callback to handle the response
273
207
  * @returns {Operation}
274
- * @example <caption>- Example `expression.js` for upserting a tracked entity instance on attribute with Id `lZGmxYbs97q`.</caption>
275
- * upsertTEI('lZGmxYbs97q', {
208
+ *
209
+ * @example <caption>-a `program`</caption>
210
+ * create('programs', {
211
+ * name: 'name 20',
212
+ * shortName: 'n20',
213
+ * programType: 'WITHOUT_REGISTRATION',
214
+ * });
215
+ *
216
+ * @example <caption>-an `event`</caption>
217
+ * create('events', {
218
+ * program: 'eBAyeGv0exc',
219
+ * orgUnit: 'DiszpKrYNg8',
220
+ * status: 'COMPLETED',
221
+ * });
222
+ *
223
+ * @example <caption>-a `trackedEntityInstance`</caption>
224
+ * create('trackedEntityInstances', {
276
225
  * orgUnit: 'TSyzvBiovKh',
277
226
  * trackedEntityType: 'nEenWmSyUEp',
278
227
  * attributes: [
279
228
  * {
280
- * attribute: 'lZGmxYbs97q',
281
- * value: '77790012',
282
- * },
283
- * {
284
229
  * attribute: 'w75KJ2mc4zz',
285
230
  * value: 'Gigiwe',
286
231
  * },
232
+ * ]
233
+ * });
234
+ *
235
+ * @example <caption>-a `dataSet`</caption>
236
+ * create('dataSets', { name: 'OpenFn Data Set', periodType: 'Monthly' });
237
+ *
238
+ * @example <caption>-a `dataSetNotification`</caption>
239
+ * create('dataSetNotificationTemplates', {
240
+ * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
241
+ * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
242
+ * name: 'Notification',
243
+ * messageTemplate: 'Hello',
244
+ * deliveryChannels: ['SMS'],
245
+ * dataSets: [],
246
+ * });
247
+ *
248
+ * @example <caption>-a `dataElement`</caption>
249
+ * create('dataElements', {
250
+ * aggregationType: 'SUM',
251
+ * domainType: 'AGGREGATE',
252
+ * valueType: 'NUMBER',
253
+ * name: 'Paracetamol',
254
+ * shortName: 'Para',
255
+ * });
256
+ *
257
+ * @example <caption>-a `dataElementGroup`</caption>
258
+ * create('dataElementGroups', {
259
+ * name: 'Data Element Group 1',
260
+ * dataElements: [],
261
+ * });
262
+ *
263
+ * @example <caption>-a `dataElementGroupSet`</caption>
264
+ * create('dataElementGroupSets', {
265
+ * name: 'Data Element Group Set 4',
266
+ * dataDimension: true,
267
+ * shortName: 'DEGS4',
268
+ * dataElementGroups: [],
269
+ * });
270
+ *
271
+ * @example <caption>-a `dataValueSet`</caption>
272
+ * create('dataValueSets', {
273
+ * dataElement: 'f7n9E0hX8qk',
274
+ * period: '201401',
275
+ * orgUnit: 'DiszpKrYNg8',
276
+ * value: '12',
277
+ * });
278
+ *
279
+ * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
280
+ * create('dataValueSets', {
281
+ * dataSet: 'pBOMPrpg1QX',
282
+ * completeDate: '2014-02-03',
283
+ * period: '201401',
284
+ * orgUnit: 'DiszpKrYNg8',
285
+ * dataValues: [
286
+ * {
287
+ * dataElement: 'f7n9E0hX8qk',
288
+ * value: '1',
289
+ * },
287
290
  * {
288
- * attribute: 'zDhUuAYrxNC',
289
- * value: 'Mwanza',
291
+ * dataElement: 'Ix2HsbDMLea',
292
+ * value: '2',
293
+ * },
294
+ * {
295
+ * dataElement: 'eY5ehpbEsB7',
296
+ * value: '3',
290
297
  * },
291
298
  * ],
292
299
  * });
293
- */
294
-
295
-
296
- function upsertTEI(uniqueAttributeId, data, options, callback) {
297
- return function (state) {
298
- var _options$apiVersion, _options, _options$strict, _options2, _body$attributes, _body$attributes$find;
299
-
300
- uniqueAttributeId = (0, _languageCommon.expandReferences)(uniqueAttributeId)(state);
301
- var body = (0, _languageCommon.expandReferences)(data)(state);
302
- options = (0, _languageCommon.expandReferences)(options)(state);
303
- if (options) options.operationName = 'upsertTEI';else {
304
- options = {
305
- operationName: 'upsertTEI'
306
- };
307
- }
308
- var _state$configuration2 = state.configuration,
309
- password = _state$configuration2.password,
310
- username = _state$configuration2.username,
311
- hostUrl = _state$configuration2.hostUrl;
312
- var apiVersion = (_options$apiVersion = (_options = options) === null || _options === void 0 ? void 0 : _options.apiVersion) !== null && _options$apiVersion !== void 0 ? _options$apiVersion : state.configuration.apiVersion;
313
- var strict = (_options$strict = (_options2 = options) === null || _options2 === void 0 ? void 0 : _options2.strict) !== null && _options$strict !== void 0 ? _options$strict : true;
314
- var params = {
315
- ou: body.orgUnit
316
- };
317
- var uniqueAttributeValue = (_body$attributes = body.attributes) === null || _body$attributes === void 0 ? void 0 : (_body$attributes$find = _body$attributes.find(function (obj) {
318
- return (obj === null || obj === void 0 ? void 0 : obj.attribute) === uniqueAttributeId;
319
- })) === null || _body$attributes$find === void 0 ? void 0 : _body$attributes$find.value;
320
- var trackedEntityType = body.trackedEntityType;
321
- var uniqueAttributeUrl = (0, _Utils.buildUrl)("/trackedEntityAttributes/".concat(uniqueAttributeId), hostUrl, apiVersion);
322
- var trackedEntityTypeUrl = (0, _Utils.buildUrl)("/trackedEntityTypes/".concat(trackedEntityType, "?fields=*"), hostUrl, apiVersion);
323
-
324
- var findTrackedEntityType = function findTrackedEntityType() {
325
- return _axios["default"].get(trackedEntityTypeUrl, {
326
- auth: {
327
- username: username,
328
- password: password
329
- }
330
- }).then(function (result) {
331
- var _result$data, _result$data$trackedE;
332
-
333
- var attribute = (_result$data = result.data) === null || _result$data === void 0 ? void 0 : (_result$data$trackedE = _result$data.trackedEntityTypeAttributes) === null || _result$data$trackedE === void 0 ? void 0 : _result$data$trackedE.find(function (obj) {
334
- var _obj$trackedEntityAtt;
335
-
336
- return (obj === null || obj === void 0 ? void 0 : (_obj$trackedEntityAtt = obj.trackedEntityAttribute) === null || _obj$trackedEntityAtt === void 0 ? void 0 : _obj$trackedEntityAtt.id) === uniqueAttributeId;
337
- });
338
- return _objectSpread({}, result.data, {
339
- upsertAttributeAssigned: attribute ? true : false
340
- });
341
- });
342
- };
343
-
344
- var isAttributeUnique = function isAttributeUnique() {
345
- return _axios["default"].get(uniqueAttributeUrl, {
346
- auth: {
347
- username: username,
348
- password: password
349
- }
350
- }).then(function (result) {
351
- var foundAttribute = result.data;
352
- return {
353
- unique: foundAttribute.unique,
354
- name: foundAttribute.name
355
- };
356
- });
357
- };
358
-
359
- return Promise.all([findTrackedEntityType(), strict === true ? isAttributeUnique() : Promise.resolve({
360
- unique: true
361
- })]).then(function (_ref) {
362
- var _ref2 = _slicedToArray(_ref, 2),
363
- entityType = _ref2[0],
364
- attribute = _ref2[1];
365
-
366
- if (!entityType.upsertAttributeAssigned) {
367
- _Utils.Log.error('');
368
-
369
- throw new RangeError("Tracked Entity Attribute ".concat(uniqueAttributeId, " is not assigned to the ").concat(entityType.name, " Entity Type."));
370
- }
371
-
372
- if (!attribute.unique) {
373
- var _attribute$name;
374
-
375
- _Utils.Log.error('');
376
-
377
- throw new RangeError("Attribute ".concat((_attribute$name = attribute.name) !== null && _attribute$name !== void 0 ? _attribute$name : '', "(").concat(uniqueAttributeId, ") is not marked as unique."));
378
- }
379
-
380
- return upsert('trackedEntityInstances', {
381
- attributeId: uniqueAttributeId,
382
- attributeValue: uniqueAttributeValue
383
- }, body, params, options, callback)(state);
384
- });
385
- };
386
- }
387
- /**
388
- * Create Tracked Entity Instance.
389
- * @public
390
- * @function
391
- * @param {Object} data - The update data containing new values.
392
- * @param {Object} [params] - Optional `import parameters` for a given a resource. E.g. `{dryRun: true, importStrategy: CREATE}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#import-parameters_1 DHIS2 Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
393
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `createTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
394
- * @param {function} [callback] - Optional callback to handle the response.
395
- * @returns {Operation}
396
- * @example <caption>- Example `expression.js` of `createTEI`.</caption>
397
- * createTEI({
398
- * orgUnit: 'TSyzvBiovKh',
399
- * trackedEntityType: 'nEenWmSyUEp',
400
- * attributes: [
401
- * {
402
- * attribute: 'lZGmxYbs97q',
403
- * value: valUpsertTEI,
404
- * },
405
- * {
406
- * attribute: 'w75KJ2mc4zz',
407
- * value: 'Gigiwe',
408
- * },
409
- * ],
410
- * enrollments: [
411
- * {
412
- * orgUnit: 'TSyzvBiovKh',
413
- * program: 'fDd25txQckK',
414
- * programState: 'lST1OZ5BDJ2',
415
- * enrollmentDate: '2021-01-04',
416
- * incidentDate: '2021-01-04',
417
- * },
418
- * ],
300
+ *
301
+ * @example <caption>-an `enrollment`</caption>
302
+ * create('enrollments', {
303
+ * trackedEntityInstance: 'bmshzEacgxa',
304
+ * orgUnit: 'TSyzvBiovKh',
305
+ * program: 'gZBxv9Ujxg0',
306
+ * enrollmentDate: '2013-09-17',
307
+ * incidentDate: '2013-09-17',
419
308
  * });
420
309
  */
421
310
 
422
311
 
423
- function createTEI(data, params, options, callback) {
424
- return function (state) {
312
+ function create(resourceType, data, options, callback) {
313
+ return state => {
314
+ console.log(`Preparing create operation...`);
315
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
316
+ data = (0, _languageCommon.expandReferences)(data)(state);
425
317
  options = (0, _languageCommon.expandReferences)(options)(state);
426
- if (options) options.operationName = 'createTEI';else {
427
- options = {
428
- operationName: 'createTEI'
429
- };
430
- }
431
- return create('trackedEntityInstances', data, params, options, callback)(state);
318
+ const {
319
+ configuration
320
+ } = state;
321
+ return (0, _Client.request)(configuration, {
322
+ method: 'post',
323
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType),
324
+ data: (0, _Utils.nestArray)(data, resourceType)
325
+ }).then(result => {
326
+ _Utils.Log.success(`Created ${resourceType}: ${result.headers.location}`);
327
+
328
+ return (0, _Utils.handleResponse)(result, state, callback);
329
+ });
432
330
  };
433
331
  }
434
332
  /**
435
- * Update a Tracked Entity Instance.
333
+ * Update data. A generic helper function to update a resource object of any type.
334
+ * Updating an object requires to send `all required fields` or the `full body`
436
335
  * @public
437
336
  * @function
438
- * @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`).
439
- * @param {Object} data - The update data containing new values.
440
- * @param {Object} [params] - Optional `import parameters` for a given a resource. E.g. `{dryRun: true, importStrategy: CREATE, filters:[]}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#import-parameters_1 DHIS2 Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
441
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `updateTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
442
- * @param {function} [callback] - Optional callback to handle the response.
337
+ * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
338
+ * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
339
+ * @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'}`
341
+ * @param {function} [callback] - Optional callback to handle the response
443
342
  * @returns {Operation}
444
- * @example <caption>- Example `expression.js` of `updateTEI`.</caption>
445
- * updateTEI('PVqUD2hvU4E', {
446
- * orgUnit: 'TSyzvBiovKh',
447
- * trackedEntityType: 'nEenWmSyUEp',
448
- * attributes: [
449
- * {
450
- * attribute: 'lZGmxYbs97q',
451
- * value: valUpsertTEI,
452
- * },
453
- * {
454
- * attribute: 'w75KJ2mc4zz',
455
- * value: 'Gigiwe',
456
- * },
457
- * ],
458
- * enrollments: [
459
- * {
460
- * orgUnit: 'TSyzvBiovKh',
461
- * program: 'fDd25txQckK',
462
- * programState: 'lST1OZ5BDJ2',
463
- * enrollmentDate: '2021-01-04',
464
- * incidentDate: '2021-01-04',
465
- * },
466
- * ],
343
+ * @example <caption>-a program</caption>
344
+ * update('programs', 'qAZJCrNJK8H', {
345
+ * name: '14e1aa02c3f0a31618e096f2c6d03bed',
346
+ * shortName: '14e1aa02',
347
+ * programType: 'WITHOUT_REGISTRATION',
467
348
  * });
468
- */
469
-
470
-
471
- function updateTEI(path, data, params, options, callback) {
472
- return function (state) {
473
- options = (0, _languageCommon.expandReferences)(options)(state);
474
- if (options) options.operationName = 'updateTEI';else {
475
- options = {
476
- operationName: 'updateTEI'
477
- };
478
- }
479
- return update('trackedEntityInstances', path, data, params, options, callback)(state);
480
- };
481
- }
482
- /**
483
- * Get annonymous events or tracker events.
484
- * @public
485
- * @function
486
- * @param {Object} params - `import` parameters for `getEvents`. See examples here
487
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getEvents` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
488
- * @param {function} [callback] - Optional callback to handle the response.
489
- * @returns {Operation}
490
- * @example <caption>- Query for `all events` with `children` of a certain `organisation unit`</caption>
491
- * getEvents({ orgUnit: 'YuQRtpLP10I', ouMode: 'CHILDREN' });
492
- */
493
-
494
-
495
- function getEvents(params, options, callback) {
496
- return function (state) {
497
- options = (0, _languageCommon.expandReferences)(options)(state);
498
- if (options) options.operationName = 'getEvents';else {
499
- options = {
500
- operationName: 'getEvents'
501
- };
502
- }
503
- return getData('events', params, responseType, options, callback)(state);
504
- };
505
- }
506
- /**
507
- * Create DHIS2 Events
508
- * - You will need a `program` which can be looked up using the `getPrograms` operation, an `orgUnit` which can be looked up using the `getMetadata` operation and passing `{organisationUnits: true}` as `resources` param, and a list of `valid data element identifiers` which can be looked up using the `getMetadata` passing `{dataElements: true}` as `resources` param.
509
- * - For events with registration, a `tracked entity instance identifier is required`
510
- * - For sending `events` to `programs with multiple stages`, you will need to also include the `programStage` identifier, the identifiers for `programStages` can be found in the `programStages` resource via a call to `getMetadata` operation.
511
- * @public
512
- * @function
513
- * @param {Object} data - The payload containing new values
514
- * @param {Object} [params] - Optional `import parameters` for events. E.g. `{dryRun: true, importStrategy: CREATE, filters:[]}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#events DHIS2 Event Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
515
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
516
- * @param {function} [callback] - Optional callback to handle the response
517
- * @returns {Operation} state
518
- * @example <caption>- Example `expression.js` of `createEvents` for a `single event` can look like this:</caption>
519
- * createEvents({
349
+ *
350
+ * @example <caption>an `event`</caption>
351
+ * update('events', 'PVqUD2hvU4E', {
520
352
  * program: 'eBAyeGv0exc',
521
- * orgUnit: 'DiszpKrYNg8',
522
- * eventDate: date,
353
+ * orgUnit: 'Ngelehun CHC',
523
354
  * status: 'COMPLETED',
524
- * completedDate: date,
525
355
  * storedBy: 'admin',
526
- * coordinate: {
527
- * latitude: 59.8,
528
- * longitude: 10.9,
529
- * },
356
+ * dataValues: [],
357
+ * });
358
+ *
359
+ * @example <caption>a `trackedEntityInstance`</caption>
360
+ * update('trackedEntityInstances', 'IeQfgUtGPq2', {
361
+ * created: '2015-08-06T21:12:37.256',
362
+ * orgUnit: 'TSyzvBiovKh',
363
+ * createdAtClient: '2015-08-06T21:12:37.256',
364
+ * trackedEntityInstance: 'IeQfgUtGPq2',
365
+ * lastUpdated: '2015-08-06T21:12:37.257',
366
+ * trackedEntityType: 'nEenWmSyUEp',
367
+ * inactive: false,
368
+ * deleted: false,
369
+ * featureType: 'NONE',
370
+ * programOwners: [
371
+ * {
372
+ * ownerOrgUnit: 'TSyzvBiovKh',
373
+ * program: 'IpHINAT79UW',
374
+ * trackedEntityInstance: 'IeQfgUtGPq2',
375
+ * },
376
+ * ],
377
+ * enrollments: [],
378
+ * relationships: [],
379
+ * attributes: [
380
+ * {
381
+ * lastUpdated: '2016-01-12T00:00:00.000',
382
+ * displayName: 'Last name',
383
+ * created: '2016-01-12T00:00:00.000',
384
+ * valueType: 'TEXT',
385
+ * attribute: 'zDhUuAYrxNC',
386
+ * value: 'Russell',
387
+ * },
388
+ * {
389
+ * lastUpdated: '2016-01-12T00:00:00.000',
390
+ * code: 'MMD_PER_NAM',
391
+ * displayName: 'First name',
392
+ * created: '2016-01-12T00:00:00.000',
393
+ * valueType: 'TEXT',
394
+ * attribute: 'w75KJ2mc4zz',
395
+ * value: 'Catherine',
396
+ * },
397
+ * ],
398
+ * });
399
+ *
400
+ * @example <caption>-a `dataSet`</caption>
401
+ * update('dataSets', 'lyLU2wR22tC', { name: 'OpenFN Data Set', periodType: 'Weekly' });
402
+ *
403
+ * @example <caption>-a `dataSetNotification`</caption>
404
+ * update('dataSetNotificationTemplates', 'VbQBwdm1wVP', {
405
+ * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
406
+ * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
407
+ * name: 'Notification',
408
+ * messageTemplate: 'Hello Updated,
409
+ * deliveryChannels: ['SMS'],
410
+ * dataSets: [],
411
+ * });
412
+ *
413
+ * @example <caption>-a `dataElement`</caption>
414
+ * update('dataElements', 'FTRrcoaog83', {
415
+ * aggregationType: 'SUM',
416
+ * domainType: 'AGGREGATE',
417
+ * valueType: 'NUMBER',
418
+ * name: 'Paracetamol',
419
+ * shortName: 'Para',
420
+ * });
421
+ *
422
+ * @example <caption>-a `dataElementGroup`</caption>
423
+ * update('dataElementGroups', 'QrprHT61XFk', {
424
+ * name: 'Data Element Group 1',
425
+ * dataElements: [],
426
+ * });
427
+ *
428
+ * @example <caption>-a `dataElementGroupSet`</caption>
429
+ * update('dataElementGroupSets', 'VxWloRvAze8', {
430
+ * name: 'Data Element Group Set 4',
431
+ * dataDimension: true,
432
+ * shortName: 'DEGS4',
433
+ * dataElementGroups: [],
434
+ * });
435
+ *
436
+ * @example <caption>-a `dataValueSet`</caption>
437
+ * update('dataValueSets', 'AsQj6cDsUq4', {
438
+ * dataElement: 'f7n9E0hX8qk',
439
+ * period: '201401',
440
+ * orgUnit: 'DiszpKrYNg8',
441
+ * value: '12',
442
+ * });
443
+ *
444
+ * @example <caption>-a `dataValueSet` with related `dataValues`</caption>
445
+ * update('dataValueSets', 'Ix2HsbDMLea', {
446
+ * dataSet: 'pBOMPrpg1QX',
447
+ * completeDate: '2014-02-03',
448
+ * period: '201401',
449
+ * orgUnit: 'DiszpKrYNg8',
530
450
  * dataValues: [
531
451
  * {
532
- * dataElement: 'qrur9Dvnyt5',
533
- * value: '33',
452
+ * dataElement: 'f7n9E0hX8qk',
453
+ * value: '1',
534
454
  * },
535
455
  * {
536
- * dataElement: 'oZg33kd9taw',
537
- * value: 'Male',
456
+ * dataElement: 'Ix2HsbDMLea',
457
+ * value: '2',
538
458
  * },
539
459
  * {
540
- * dataElement: 'msodh3rEMJa',
541
- * value: date,
460
+ * dataElement: 'eY5ehpbEsB7',
461
+ * value: '3',
542
462
  * },
543
463
  * ],
544
464
  * });
465
+ *
466
+ * @example <caption>a single enrollment</caption>
467
+ * update('enrollments', 'CmsHzercTBa' {
468
+ * trackedEntityInstance: 'bmshzEacgxa',
469
+ * orgUnit: 'TSyzvBiovKh',
470
+ * program: 'gZBxv9Ujxg0',
471
+ * enrollmentDate: '2013-10-17',
472
+ * incidentDate: '2013-10-17',
473
+ * });
545
474
  */
546
475
 
547
476
 
548
- function createEvents(data, params, options, callback) {
549
- return function (state) {
477
+ function update(resourceType, path, data, options, callback) {
478
+ return state => {
479
+ console.log(`Preparing update operation...`);
480
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
481
+ path = (0, _languageCommon.expandReferences)(path)(state);
482
+ data = (0, _languageCommon.expandReferences)(data)(state);
550
483
  options = (0, _languageCommon.expandReferences)(options)(state);
551
- if (options) options.operationName = 'createEvents';else {
552
- options = {
553
- operationName: 'createEvents'
554
- };
555
- }
556
- return create('events', data, params, options, callback)(state);
484
+ const {
485
+ configuration
486
+ } = state;
487
+ return (0, _Client.request)(configuration, {
488
+ method: 'put',
489
+ url: `${(0, _Utils.generateUrl)(configuration, options, resourceType)}/${path}`,
490
+ // TODO: @Elias, why no "nestArray" here?
491
+ data
492
+ }).then(result => {
493
+ _Utils.Log.success(`Updated ${resourceType} at ${path}`);
494
+
495
+ return (0, _Utils.handleResponse)(result, state, callback);
496
+ });
557
497
  };
558
498
  }
559
499
  /**
560
- * Update DHIS2 Event.
561
- * - To update an existing event, the format of the payload is the same as that of `creating an event` via `createEvents` operations
562
- * - But you should supply the `identifier` of the object you are updating
563
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
564
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
565
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
500
+ * Get data. Generic helper method for getting data of any kind from DHIS2.
501
+ * - This can be used to get `DataValueSets`,`events`,`trackedEntityInstances`,`etc.`
566
502
  * @public
567
503
  * @function
568
- * @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
569
- * @param {Object} data - The update data containing new values
570
- * @param {Object} [params] - Optional `import` parameters for `updateEvents`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
571
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
572
- * @param {function} [callback] - Optional callback to handle the response
573
- * @returns {Operation}
574
- * @example <caption>- Example `expression.js` of `updateEvents`</caption>
575
- * updateEvents('PVqUD2hvU4E', { events: [
576
- * {
577
- * program: 'eBAyeGv0exc',
578
- * orgUnit: 'DiszpKrYNg8',
579
- * eventDate: date,
580
- * status: 'COMPLETED',
581
- * storedBy: 'admin',
582
- * coordinate: {
583
- * latitude: '59.8',
584
- * longitude: '10.9',
585
- * },
586
- * dataValues: [
587
- * {
588
- * dataElement: 'qrur9Dvnyt5',
589
- * value: '22',
590
- * },
591
- * {
592
- * dataElement: 'oZg33kd9taw',
593
- * value: 'Male',
594
- * },
595
- * ],
596
- * }]
504
+ * @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'}`.
506
+ * @param {function} [callback] - Optional callback to handle the response
507
+ * @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',
597
514
  * });
598
515
  */
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?
599
518
 
600
519
 
601
- function updateEvents(path, data, params, options, callback) {
602
- return function (state) {
520
+ function get(resourceType, options, callback) {
521
+ return state => {
522
+ console.log(`Preparing get operation...`);
523
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
603
524
  options = (0, _languageCommon.expandReferences)(options)(state);
604
- if (options) options.operationName = 'updateEvents';else {
605
- options = {
606
- operationName: 'updateEvents'
607
- };
608
- }
609
- return update('events', path, data, params, options, callback)(state);
525
+ const {
526
+ configuration
527
+ } = state;
528
+ return (0, _Client.request)(configuration, {
529
+ method: 'get',
530
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType),
531
+ params: (0, _Utils.buildUrlParams)(options),
532
+ responseType: 'json'
533
+ }).then(result => {
534
+ _Utils.Log.success(`Retrieved ${result.data[resourceType].length} ${resourceType}.`);
535
+
536
+ return (0, _Utils.handleResponse)(result, state, callback);
537
+ });
610
538
  };
611
539
  }
612
540
  /**
613
- * Get DHIS2 Tracker Programs.
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.
614
542
  * @public
615
543
  * @function
616
- * @param {Object} params - `import` parameters for `getPrograms`. See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#tracker-web-api DHIS2 api documentation for allowed query parameters }
617
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
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'}`.
618
547
  * @param {function} [callback] - Optional callback to handle the response
548
+ * @throws {RangeError} - Throws range error
619
549
  * @returns {Operation}
620
- * @example <caption>- Query for `all programs` with a certain `organisation unit`</caption>
621
- * getPrograms({ orgUnit: 'DiszpKrYNg8' , fields: '*' });
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
622
566
  */
623
567
 
624
568
 
625
- function getPrograms(params, options, callback) {
626
- return function (state) {
627
- options = (0, _languageCommon.expandReferences)(options)(state);
628
- if (options) options.operationName = 'getPrograms';else {
629
- options = {
630
- operationName: 'getPrograms'
631
- };
632
- }
633
- return getData('programs', params, options, callback)(state);
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
+ });
634
585
  };
635
586
  }
636
587
  /**
637
- * Create a DHIS2 Tracker Program
638
- * @public
639
- * @function
640
- * @param {Object} data - The update data containing new values
641
- * @param {Object} [params] - Optional `import` parameters for `createPrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
642
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
643
- * @param {function} [callback] - Optional callback to handle the response
644
- * @returns {Operation}
645
- * @example <caption>- Example `expression.js` of `createPrograms` for a `single program` can look like this:</caption>
646
- * createPrograms(state.data);
647
- */
648
-
649
-
650
- function createPrograms(data, params, options, callback) {
651
- return function (state) {
652
- options = (0, _languageCommon.expandReferences)(options)(state);
653
- if (options) options.operationName = 'createPrograms';else {
654
- options = {
655
- operationName: 'createPrograms'
656
- };
657
- }
658
- return create('programs', data, options, params, callback)(state);
659
- };
660
- }
661
- /**
662
- * Update DHIS2 Tracker Programs
663
- * - To update an existing program, the format of the payload is the same as that of `creating an event` via `createEvents` operations
664
- * - But you should supply the `identifier` of the object you are updating
665
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
666
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
667
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
668
- * @public
669
- * @function
670
- * @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
671
- * @param {Object} data - The update data containing new values
672
- * @param {Object} [params] - Optional `import` parameters for `updatePrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
673
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
674
- * @param {function} [callback] - Optional callback to handle the response
675
- * @returns {Operation}
676
- * @example <caption>- Example `expression.js` of `updatePrograms`</caption>
677
- * updatePrograms('PVqUD2hvU4E', state.data);
678
- */
679
-
680
-
681
- function updatePrograms(path, data, params, options, callback) {
682
- return function (state) {
683
- options = (0, _languageCommon.expandReferences)(options)(state);
684
- if (options) options.operationName = 'updatePrograms';else {
685
- options = {
686
- operationName: 'updatePrograms'
687
- };
688
- }
689
- return update('programs', path, data, params, options, callback)(state);
690
- };
691
- }
692
- /**
693
- * Get DHIS2 Enrollments
694
- * @public
695
- * @function
696
- * @param {Object} params - `Query` parameters for `getEnrollments`. See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#enrollment-management here}
697
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
698
- * @param {function} [callback] - Optional callback to handle the response
699
- * @returns {Operation}
700
- * @example <caption>- To constrain the response to `enrollments` which are part of a `specific program` you can include a `program query parameter`</caption>
701
- * getEnrollments({
702
- * ou: 'O6uvpzGd5pu',
703
- * ouMode: 'DESCENDANTS',
704
- * program: 'ur1Edk5Oe2n',
705
- * fields: '*',
706
- * });
707
- */
708
-
709
-
710
- function getEnrollments(params, options, callback) {
711
- return function (state) {
712
- options = (0, _languageCommon.expandReferences)(options)(state);
713
- if (options) options.operationName = 'getEnrollments';else {
714
- options = {
715
- operationName: 'getEnrollments'
716
- };
717
- }
718
- return getData('enrollments', params, options, callback)(state);
719
- };
720
- }
721
- /**
722
- * Enroll a TEI into a program
723
- * - Enrolling a tracked entity instance into a program
724
- * - For enrolling `persons` into a `program`, you will need to first get the `identifier of the person` from the `trackedEntityInstances resource` via the `getTEIs` operation.
725
- * - Then, you will need to get the `program identifier` from the `programs` resource via the `getPrograms` operation.
726
- * @public
727
- * @function
728
- * @param {Object} data - The enrollment data. See example {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#enrollment-management here }
729
- * @param {Object} [params] - Optional `import` parameters for `createEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
730
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `enrollTEI` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
731
- * @param {function} [callback] - Optional callback to handle the response
732
- * @returns {Operation}
733
- * @example <caption>- Example `expression.js` of `createEnrollment` of a `person` into a `program` can look like this:</caption>
734
- * enrollTEI({
735
- * trackedEntity: 'tracked-entity-id',
736
- * orgUnit: 'org-unit-id',
737
- * attributes: [
738
- * {
739
- * attribute: 'attribute-id',
740
- * value: 'attribute-value',
741
- * },
742
- * ],
743
- * enrollments: [
744
- * {
745
- * orgUnit: 'org-unit-id',
746
- * program: 'program-id',
747
- * enrollmentDate: '2013-09-17',
748
- * incidentDate: '2013-09-17',
749
- * },
750
- * ],
751
- *});
752
- */
753
-
754
-
755
- function enrollTEI(data, params, options, callback) {
756
- return function (state) {
757
- options = (0, _languageCommon.expandReferences)(options)(state);
758
- if (options) options.operationName = 'enrollTEI';else {
759
- options = {
760
- operationName: 'enrollTEI'
761
- };
762
- }
763
- return create('enrollments', data, options, params, callback)(state);
764
- };
765
- }
766
- /**
767
- * Update a DHIS2 Enrollemts
768
- * - To update an existing enrollment, the format of the payload is the same as that of `creating an event` via `createEvents` operations
769
- * - But you should supply the `identifier` of the object you are updating
770
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
771
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
772
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
773
- * @public
774
- * @function
775
- * @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
776
- * @param {Object} data - The update data containing new values
777
- * @param {Object} [params] - Optional `import` parameters for `updateEnrollments`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
778
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
779
- * @param {function} [callback] - Optional callback to handle the response
780
- * @returns {Operation}
781
- * @example <caption>- Example `expression.js` of `updateEnromments`</caption>
782
- * updateEnrollments('PVqUD2hvU4E', state.data);
783
- */
784
-
785
-
786
- function updateEnrollments(path, data, params, options, callback) {
787
- return function (state) {
788
- options = (0, _languageCommon.expandReferences)(options)(state);
789
- if (options) options.operationName = 'updateEnrollments';else {
790
- options = {
791
- operationName: 'updateEnrollments'
792
- };
793
- }
794
- return update('enrollments', path, data, params, options, callback)(state);
795
- };
796
- }
797
- /**
798
- * Cancel a DHIS2 Enrollment
799
- * - To cancel an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
800
- * @public
801
- * @function
802
- * @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
803
- * @param {Object} [params] - Optional `import` parameters for `cancelEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
804
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `cancelEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
805
- * @param {function} [callback] - Optional callback to handle the response
806
- * @returns {Operation}
807
- * @example <caption>- Example `expression.js` of `cancelEnrollment`</caption>
808
- * cancelEnrollments('PVqUD2hvU4E');
809
- */
810
-
811
-
812
- function cancelEnrollment(enrollmentId, params, options, callback) {
813
- return function (state) {
814
- enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
815
- options = (0, _languageCommon.expandReferences)(options)(state);
816
- if (options) options.operationName = 'cancelEnrollment';else {
817
- options = {
818
- operationName: 'cancelEnrollment'
819
- };
820
- }
821
- var path = "".concat(enrollmentId, "/cancelled");
822
- return update('enrollments', path, null, params, options, callback)(state);
823
- };
824
- }
825
- /**
826
- * Complete a DHIS2 Enrollment
827
- * - To complete an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
828
- * @public
829
- * @function
830
- * @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
831
- * @param {Object} [params] - Optional `import` parameters for `completeEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
832
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `completeEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
833
- * @param {function} [callback] - Optional callback to handle the response
834
- * @returns {Operation}
835
- * @example <caption>- Example `expression.js` of `completeEnrollment`</caption>
836
- * completeEnrollment('PVqUD2hvU4E');
837
- */
838
-
839
-
840
- function completeEnrollment(enrollmentId, params, options, callback) {
841
- return function (state) {
842
- enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
843
- options = (0, _languageCommon.expandReferences)(options)(state);
844
- if (options) options.operationName = 'completeEnrollment';else {
845
- options = {
846
- operationName: 'completeEnrollment'
847
- };
848
- }
849
- var path = "".concat(enrollmentId, "/completed");
850
- return update('enrollments', path, null, params, options, callback)(state);
851
- };
852
- }
853
- /**
854
- * Get DHIS2 Relationships(links) between two entities in tracker. These entities can be tracked entity instances, enrollments and events.
855
- * - All the tracker operations, `getTEIs`, `getEnrollments` and `getEvents` also list their relationships if requested in the `field` filter.
856
- * - To list all relationships, this requires you to provide the UID of the trackedEntityInstance, Enrollment or event that you want to list all the relationships for.
857
- * @public
858
- * @function
859
- * @param {Object} params - `Query` parameters for `getRelationships`. See examples {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#relationships here}
860
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getRelationships` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
861
- * @param {function} [callback] - Optional callback to handle the response
862
- * @returns {Operation}
863
- * @example <caption>- A query for `all relationships` associated with a `specific tracked entity instance` can look like this:</caption>
864
- * getRelationships({ tei: 'F8yKM85NbxW', fields: '*' });
865
- */
866
-
867
-
868
- function getRelationships(params, options, callback) {
869
- return function (state) {
870
- options = (0, _languageCommon.expandReferences)(options)(state);
871
- if (options) options.operationName = 'getRelationships';else {
872
- options = {
873
- operationName: 'getRelationships'
874
- };
875
- }
876
- return getData('relationships', params, options, callback)(state);
877
- };
878
- }
879
- /**
880
- * Get DHIS2 Data Values.
881
- * - This operation retrives data values from DHIS2 Web API by interacting with the `dataValueSets` resource
882
- * - Data values can be retrieved in XML, JSON and CSV format.
883
- * @public
884
- * @function
885
- * @param {Object} params - `Query` parameters for `getDataValues`. E.g. `{dataset: 'pBOMPrpg1QX', limit: 3, period: 2021, orgUnit: 'DiszpKrYNg8'} Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#data-values DHIS2 API docs} for available `Data Value Set Query Parameters`.
886
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `options` for `getDataValues` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`
887
- * @param {function} [callback] - Optional `callback` to handle the response
888
- * @returns {Operation}
889
- * @example <caption>- Example getting **two** `data values` associated with a specific `orgUnit`, `dataSet`, and `period `</caption>
890
- * getDataValues({
891
- * orgUnit: 'DiszpKrYNg8',
892
- * period: '202010',
893
- * dataSet: 'pBOMPrpg1QX',
894
- * limit: 2,
895
- * });
896
- */
897
-
898
-
899
- function getDataValues(params, options, callback) {
900
- return function (state) {
901
- options = (0, _languageCommon.expandReferences)(options)(state);
902
- if (options) options.operationName = 'getDataValues';else {
903
- options = {
904
- operationName: 'getDataValues'
905
- };
906
- }
907
- return getData('dataValueSets', params, options, callback)(state);
908
- };
909
- }
910
- /**
911
- * Create DHIS2 Data Values
912
- * - This is used to send aggregated data to DHIS2
913
- * - A data value set represents a set of data values which have a relationship, usually from being captured off the same data entry form.
914
- * - To send a set of related data values sharing the same period and organisation unit, we need to identify the period, the data set, the org unit (facility) and the data elements for which to report.
915
- * - You can also use this operation to send large bulks of data values which don't necessarily are logically related.
916
- * - To send data values that are not linked to a `dataSet`, you do not need to specify the dataSet and completeDate attributes. Instead, you will specify the period and orgUnit attributes on the individual data value elements instead of on the outer data value set element. This will enable us to send data values for various periods and organisation units
917
- * @public
918
- * @function
919
- * @param {object} data - The `data values` to upload or create. See example shape.
920
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createDataVaues` operation.
921
- * @param {object} [params] - Optional `import` parameters for `createDataValues`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`. Run `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#data-values DHIS2 Docs API} to learn about available data values import parameters.
922
- * @param {function} [callback] - Optional callback to handle the response
923
- * @returns {Operation}
924
- * @example <caption>- Example `expression.js` of `createDataValues` for sending a set of related data values sharing the same period and organisation unit</caption>
925
- * createDataValues({
926
- * dataSet: 'pBOMPrpg1QX',
927
- * completeDate: '2014-02-03',
928
- * period: '201401',
929
- * orgUnit: 'DiszpKrYNg8',
930
- * dataValues: [
931
- * {
932
- * dataElement: 'f7n9E0hX8qk',
933
- * value: '1',
934
- * },
935
- * {
936
- * dataElement: 'Ix2HsbDMLea',
937
- * value: '2',
938
- * },
939
- * {
940
- * dataElement: 'eY5ehpbEsB7',
941
- * value: '3',
942
- * },
943
- * ],
944
- * });
945
- */
946
-
947
-
948
- function createDataValues(data, options, params, callback) {
949
- return function (state) {
950
- options = (0, _languageCommon.expandReferences)(options)(state);
951
- if (options) options.operationName = 'createDataValues';else {
952
- options = {
953
- operationName: 'createDataValues'
954
- };
955
- }
956
- return create('dataValueSets', data, options, params, callback)(state);
957
- };
958
- }
959
- /**
960
- * Generate valid, random DHIS2 identifiers
961
- * - Useful for client generated Ids compatible with DHIS2
962
- * @public
963
- * @function
964
- * @param {{apiVersion: number,limit: number,responseType: string}} [options] - Optional `options` for `generateDhis2UID` operation. Defaults to `{apiVersion: state.configuration.apiVersion,limit: 1,responseType: 'json'}`
965
- * @param {function} [callback] - Callback to handle response
966
- * @returns {Operation}
967
- * @example <caption>Example generating `three UIDs` from the DHIS2 server</caption>
968
- * generateDhis2UID({limit: 3});
969
- */
970
-
971
-
972
- function generateDhis2UID(options, callback) {
973
- return function (state) {
974
- var _options$limit, _options3, _options4;
975
-
976
- options = (0, _languageCommon.expandReferences)(options)(state);
977
- if (options) options.operationName = 'generateDhis2UID';else {
978
- options = {
979
- operationName: 'generateDhis2UID'
980
- };
981
- }
982
- var limit = {
983
- limit: (_options$limit = (_options3 = options) === null || _options3 === void 0 ? void 0 : _options3.limit) !== null && _options$limit !== void 0 ? _options$limit : 1
984
- };
985
- (_options4 = options) === null || _options4 === void 0 ? true : delete _options4.limit;
986
- return getData('system/id', limit, options, callback)(state);
987
- };
988
- }
989
- /**
990
- * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
588
+ * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
991
589
  * @public
992
590
  * @function
993
591
  * @param {string} httpMethod - The HTTP to inspect parameter usage for a given endpoint, e.g., `get`, `post`,`put`,`patch`,`delete`
@@ -999,27 +597,26 @@ function generateDhis2UID(options, callback) {
999
597
 
1000
598
 
1001
599
  function discover(httpMethod, endpoint) {
1002
- return function (state) {
1003
- _Utils.Log.info("Discovering query/import parameters for ".concat(httpMethod, " on ").concat(endpoint));
1004
-
1005
- return _axios["default"].get('https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json', {
1006
- transformResponse: [function (data) {
1007
- var tempData = JSON.parse(data);
1008
- var filteredData = tempData.paths[endpoint][httpMethod];
1009
- return _objectSpread({}, filteredData, {
1010
- parameters: filteredData.parameters.reduce(function (acc, currentValue) {
1011
- var index = currentValue['$ref'].lastIndexOf('/') + 1;
1012
- var paramRef = currentValue['$ref'].slice(index);
1013
- var param = tempData.components.parameters[paramRef];
600
+ return state => {
601
+ console.log(`Discovering query/import parameters for ${httpMethod} on ${endpoint}`);
602
+ return _axios.default.get('https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json', {
603
+ transformResponse: [data => {
604
+ let tempData = JSON.parse(data);
605
+ let filteredData = tempData.paths[endpoint][httpMethod];
606
+ return { ...filteredData,
607
+ parameters: filteredData.parameters.reduce((acc, currentValue) => {
608
+ let index = currentValue['$ref'].lastIndexOf('/') + 1;
609
+ let paramRef = currentValue['$ref'].slice(index);
610
+ let param = tempData.components.parameters[paramRef];
1014
611
 
1015
612
  if (param.schema['$ref']) {
1016
- var schemaRefIndex = param.schema['$ref'].lastIndexOf('/') + 1;
1017
- var schemaRef = param.schema['$ref'].slice(schemaRefIndex);
613
+ let schemaRefIndex = param.schema['$ref'].lastIndexOf('/') + 1;
614
+ let schemaRef = param.schema['$ref'].slice(schemaRefIndex);
1018
615
  param.schema = tempData.components.schemas[schemaRef];
1019
616
  }
1020
617
 
1021
618
  param.schema = JSON.stringify(param.schema);
1022
- var descIndex;
619
+ let descIndex;
1023
620
  if ((0, _lodash.indexOf)(param.description, ',') === -1 && (0, _lodash.indexOf)(param.description, '.') > -1) descIndex = (0, _lodash.indexOf)(param.description, '.');else if ((0, _lodash.indexOf)(param.description, ',') > -1 && (0, _lodash.indexOf)(param.description, '.') > -1) {
1024
621
  descIndex = (0, _lodash.indexOf)(param.description, '.') < (0, _lodash.indexOf)(param.description, ',') ? (0, _lodash.indexOf)(param.description, '.') : (0, _lodash.indexOf)(param.description, ',');
1025
622
  } else {
@@ -1029,496 +626,18 @@ function discover(httpMethod, endpoint) {
1029
626
  acc[paramRef] = param;
1030
627
  return acc;
1031
628
  }, {})
1032
- });
629
+ };
1033
630
  }]
1034
- }).then(function (result) {
631
+ }).then(result => {
1035
632
  var _result$data$descript;
1036
633
 
1037
- _Utils.Log.info("\t=======================================================================================\n\tQuery Parameters for ".concat(httpMethod, " on ").concat(endpoint, " [").concat((_result$data$descript = result.data.description) !== null && _result$data$descript !== void 0 ? _result$data$descript : '<description_missing>', "]\n\t======================================================================================="));
1038
-
634
+ console.log(`\t=======================================================================================\n\tQuery Parameters for ${httpMethod} on ${endpoint} [${(_result$data$descript = result.data.description) !== null && _result$data$descript !== void 0 ? _result$data$descript : '<description_missing>'}]\n\t=======================================================================================`);
1039
635
  console.table(result.data.parameters, ['in', 'required', 'description']);
1040
636
  console.table(result.data.parameters, ['schema']);
1041
- console.log("=========================================Responses===============================\n".concat((0, _Utils.prettyJson)(result.data.responses), "\n======================================================================================="));
1042
- return _objectSpread({}, state, {
637
+ console.log(`=========================================Responses===============================\n${(0, _Utils.prettyJson)(result.data.responses)}\n=======================================================================================`);
638
+ return { ...state,
1043
639
  data: result.data
1044
- });
1045
- });
1046
- };
1047
- }
1048
- /**
1049
- * Get analytical, aggregated data
1050
- * - The analytics resource is powerful as it lets you query and retrieve data aggregated along all available data dimensions.
1051
- * - For instance, you can ask the analytics resource to provide the aggregated data values for a set of data elements, periods and organisation units.
1052
- * - Also, you can retrieve the aggregated data for a combination of any number of dimensions based on data elements and organisation unit group sets.
1053
- * @public
1054
- * @function
1055
- * @param {Object} params - Analytics `query parameters`, e.g. `{dx: 'fbfJHSPpUQD;cYeuwXTCPkU',filters: ['pe:2014Q1;2014Q2','ou:O6uvpzGd5pu;lc3eMKXaEfw']}`. Run `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#analytics DHIS2 API docs} to get the params available.
1056
- * @param {{apiVersion: number,responseType: string}}[options] - `Optional` options for `getAnalytics` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
1057
- * @param {function} [callback] - Callback to handle response
1058
- * @returns {Operation}
1059
- * @example <caption>Example getting only records where the data value is greater or equal to 6500 and less than 33000</caption>
1060
- * getAnalytics({
1061
- * dimensions: [
1062
- * 'dx:fbfJHSPpUQD;cYeuwXTCPkU',
1063
- * 'pe:2014',
1064
- * 'ou:O6uvpzGd5pu;lc3eMKXaEfw',
1065
- * ],
1066
- * measureCriteria: 'GE:6500;LT:33000',
1067
- * });
1068
- */
1069
-
1070
-
1071
- function getAnalytics(params, options, callback) {
1072
- return function (state) {
1073
- options = (0, _languageCommon.expandReferences)(options)(state);
1074
- if (options) options.operationName = 'getAnalytics';else {
1075
- options = {
1076
- operationName: 'getAnalytics'
1077
640
  };
1078
- }
1079
- return getData("analytics", params, options, callback)(state);
1080
- };
1081
- }
1082
- /**
1083
- * Get DHIS2 api resources
1084
- * @public
1085
- * @function
1086
- * @param {Object} [params] - The `optional` query parameters for this endpoint. E.g `{filter: 'singular:like:attribute'}`.
1087
- * @param {{filter: string, fields: string, responseType: string}} [options] - The `optional` options, specifiying the filter expression. E.g. `singular:eq:attribute`.
1088
- * @param {function} [callback] - The `optional callback function that will be called to handle data returned by this function.
1089
- * @returns {Operation}
1090
- * @example <caption>Example getting a resource named `attribute`, in `xml` format, returning all the fields</caption>
1091
- * getResources('dataElement', {
1092
- * filter: 'singular:eq:attribute',
1093
- * fields: '*',
1094
- * responseType: 'xml',
1095
- * });
1096
- */
1097
-
1098
-
1099
- function getResources(params, options, callback) {
1100
- return function (state) {
1101
- var _options$responseType, _options5, _params, _CONTENT_TYPES$respon;
1102
-
1103
- params = (0, _languageCommon.expandReferences)(params)(state);
1104
- options = (0, _languageCommon.expandReferences)(options)(state);
1105
- var operationName = 'getResources';
1106
- var _state$configuration3 = state.configuration,
1107
- username = _state$configuration3.username,
1108
- password = _state$configuration3.password,
1109
- hostUrl = _state$configuration3.hostUrl;
1110
- var responseType = (_options$responseType = (_options5 = options) === null || _options5 === void 0 ? void 0 : _options5.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : 'json';
1111
- var filter = (_params = params) === null || _params === void 0 ? void 0 : _params.filter;
1112
- var queryParams = params;
1113
- var headers = {
1114
- Accept: (_CONTENT_TYPES$respon = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon !== void 0 ? _CONTENT_TYPES$respon : 'application/json'
1115
- };
1116
- var path = '/resources';
1117
- var url = (0, _Utils.buildUrl)(path, hostUrl, null, false);
1118
-
1119
- var transformResponse = function transformResponse(data, headers) {
1120
- if (filter) {
1121
- var _headers$contentType, _headers$contentType2;
1122
-
1123
- if (((_headers$contentType = (_headers$contentType2 = headers['content-type']) === null || _headers$contentType2 === void 0 ? void 0 : _headers$contentType2.split(';')[0]) !== null && _headers$contentType !== void 0 ? _headers$contentType : null) === _Utils.CONTENT_TYPES.json) {
1124
- var tempData = JSON.parse(data);
1125
- return _objectSpread({}, tempData, {
1126
- resources: _Utils.applyFilter.apply(void 0, [tempData.resources].concat(_toConsumableArray((0, _Utils.parseFilter)(filter))))
1127
- });
1128
- } else {
1129
- _Utils.Log.warn('Filters on this resource are only supported for json content types. Skipping filtering ...');
1130
- }
1131
- }
1132
-
1133
- return data;
1134
- };
1135
-
1136
- (0, _Utils.logOperation)(operationName);
1137
- (0, _Utils.logWaitingForServer)(url, queryParams);
1138
- (0, _Utils.warnExpectLargeResult)(queryParams, url);
1139
- return _axios["default"].request({
1140
- url: url,
1141
- method: 'GET',
1142
- auth: {
1143
- username: username,
1144
- password: password
1145
- },
1146
- responseType: responseType,
1147
- headers: headers,
1148
- params: queryParams,
1149
- transformResponse: transformResponse
1150
- }).then(function (result) {
1151
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your ").concat(operationName, " callback."));
1152
-
1153
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1154
- return (0, _languageCommon.composeNextState)(state, result.data);
1155
- });
1156
- };
1157
- }
1158
- /**
1159
- * Get schema of a given resource type, in any data format supported by DHIS2
1160
- * @public
1161
- * @function
1162
- * @param {string} resourceType - The type of resource to be updated(`singular` version of the `resource name`). E.g. `dataElement`, `organisationUnit`, etc. Run `getResources` to see available resources and their corresponding `singular` names.
1163
- * @param {Object} params - Optional `query parameters` for the `getSchema` operation. e.g. `{ fields: 'properties' ,skipPaging: true}`. Run`discover` or See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#metadata-export-examples DHIS2 API Docs}
1164
- * @param {{apiVersion: number,resourceType: string}} [options] - Optional options for `getSchema` method. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1165
- * @param {function} [callback] - Optional `callback` to handle the response
1166
- * @returns {Operation}
1167
- * @example <caption>Example getting the `schema` for `dataElement` in XML</caption>
1168
- * getSchema('dataElement', '{ fields: '*' }, { responseType: 'xml' });
1169
- */
1170
-
1171
-
1172
- function getSchema(resourceType, params, options, callback) {
1173
- return function (state) {
1174
- var _options$responseType2, _options6, _params2, _params3, _options$apiVersion2, _options7, _CONTENT_TYPES$respon2, _resourceType;
1175
-
1176
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1177
- params = (0, _languageCommon.expandReferences)(params)(state);
1178
- options = (0, _languageCommon.expandReferences)(options)(state);
1179
- var operationName = 'getSchema';
1180
- var _state$configuration4 = state.configuration,
1181
- username = _state$configuration4.username,
1182
- password = _state$configuration4.password,
1183
- hostUrl = _state$configuration4.hostUrl;
1184
- var responseType = (_options$responseType2 = (_options6 = options) === null || _options6 === void 0 ? void 0 : _options6.responseType) !== null && _options$responseType2 !== void 0 ? _options$responseType2 : 'json';
1185
- var filters = (_params2 = params) === null || _params2 === void 0 ? void 0 : _params2.filters;
1186
- (_params3 = params) === null || _params3 === void 0 ? true : delete _params3.filters;
1187
- var queryParams = new URLSearchParams(params);
1188
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1189
- return queryParams.append('filter', f);
1190
- });
1191
- var apiVersion = (_options$apiVersion2 = (_options7 = options) === null || _options7 === void 0 ? void 0 : _options7.apiVersion) !== null && _options$apiVersion2 !== void 0 ? _options$apiVersion2 : state.configuration.apiVersion;
1192
- var headers = {
1193
- Accept: (_CONTENT_TYPES$respon2 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon2 !== void 0 ? _CONTENT_TYPES$respon2 : 'application/json'
1194
- };
1195
- var url = (0, _Utils.buildUrl)("/schemas/".concat((_resourceType = resourceType) !== null && _resourceType !== void 0 ? _resourceType : ''), hostUrl, apiVersion);
1196
- (0, _Utils.logOperation)(operationName);
1197
- (0, _Utils.logApiVersion)(apiVersion);
1198
- (0, _Utils.logWaitingForServer)(url, queryParams);
1199
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1200
- return _axios["default"].request({
1201
- method: 'GET',
1202
- url: url,
1203
- auth: {
1204
- username: username,
1205
- password: password
1206
- },
1207
- responseType: responseType,
1208
- params: queryParams,
1209
- headers: headers
1210
- }).then(function (result) {
1211
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your ").concat(operationName, " callback."));
1212
-
1213
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1214
- return (0, _languageCommon.composeNextState)(state, result.data);
1215
- });
1216
- };
1217
- }
1218
- /**
1219
- * Get data. Generic helper method for getting data of any kind from DHIS2.
1220
- * - This can be used to get `DataValueSets`,`events`,`trackedEntityInstances`,`etc.`
1221
- * @public
1222
- * @function
1223
- * @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `trackedEntityInstances`,`organisationUnits`, etc.
1224
- * @param {Object} [params] - Optional `query parameters` e.g. `{ou: 'DiszpKrYNg8'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html DHIS2 docs} for more details on which params to use for a given type of resource.
1225
- * @param {{apiVersion: number,operationName: string,responseType: string}}[options] - `Optional` options for `getData` operation. Defaults to `{operationName: 'getData', apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
1226
- * @param {function} [callback] - Optional callback to handle the response
1227
- * @returns {Operation} state
1228
- * @example <caption>Example getting one `trackedEntityInstance` with `Id` 'dNpxRu1mWG5' for a given `orgUnit(DiszpKrYNg8)`</caption>
1229
- * getData('trackedEntityInstances', {
1230
- * fields: '*',
1231
- * ou: 'DiszpKrYNg8',
1232
- * entityType: 'nEenWmSyUEp',
1233
- * trackedEntityInstance: 'dNpxRu1mWG5',
1234
- * });
1235
- */
1236
-
1237
-
1238
- function getData(resourceType, params, options, callback) {
1239
- return function (state) {
1240
- var _options$operationNam, _options8, _options$responseType3, _options9, _params4, _params5, _params6, _options$apiVersion3, _options10, _CONTENT_TYPES$respon3;
1241
-
1242
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1243
- params = (0, _languageCommon.expandReferences)(params)(state);
1244
- options = (0, _languageCommon.expandReferences)(options)(state);
1245
- var operationName = (_options$operationNam = (_options8 = options) === null || _options8 === void 0 ? void 0 : _options8.operationName) !== null && _options$operationNam !== void 0 ? _options$operationNam : 'getData';
1246
- var _state$configuration5 = state.configuration,
1247
- username = _state$configuration5.username,
1248
- password = _state$configuration5.password,
1249
- hostUrl = _state$configuration5.hostUrl;
1250
- var responseType = (_options$responseType3 = (_options9 = options) === null || _options9 === void 0 ? void 0 : _options9.responseType) !== null && _options$responseType3 !== void 0 ? _options$responseType3 : 'json';
1251
- var filters = (_params4 = params) === null || _params4 === void 0 ? void 0 : _params4.filters;
1252
- var dimensions = (_params5 = params) === null || _params5 === void 0 ? void 0 : _params5.dimensions;
1253
- (_params6 = params) === null || _params6 === void 0 ? true : delete _params6.filters;
1254
- var queryParams = new URLSearchParams(params);
1255
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1256
- return queryParams.append('filter', f);
1257
- });
1258
- dimensions === null || dimensions === void 0 ? void 0 : dimensions.map(function (d) {
1259
- return queryParams.append('dimension', d);
1260
- });
1261
- var apiVersion = (_options$apiVersion3 = (_options10 = options) === null || _options10 === void 0 ? void 0 : _options10.apiVersion) !== null && _options$apiVersion3 !== void 0 ? _options$apiVersion3 : state.configuration.apiVersion;
1262
- var headers = {
1263
- Accept: (_CONTENT_TYPES$respon3 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon3 !== void 0 ? _CONTENT_TYPES$respon3 : 'application/json'
1264
- };
1265
- var url = (0, _Utils.buildUrl)("/".concat(resourceType), hostUrl, apiVersion);
1266
- (0, _Utils.logOperation)(operationName);
1267
- (0, _Utils.logApiVersion)(apiVersion);
1268
- (0, _Utils.logWaitingForServer)(url, queryParams);
1269
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1270
- return _axios["default"].request({
1271
- method: 'GET',
1272
- url: url,
1273
- auth: {
1274
- username: username,
1275
- password: password
1276
- },
1277
- responseType: responseType,
1278
- params: queryParams,
1279
- headers: headers
1280
- }).then(function (result) {
1281
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your callback."));
1282
-
1283
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1284
- return (0, _languageCommon.composeNextState)(state, result.data);
1285
- });
1286
- };
1287
- }
1288
- /**
1289
- * Get metadata. A generic helper function to get metadata records from a given DHIS2 instance
1290
- * @public
1291
- * @function
1292
- * @param {string[]} resources - Required. List of metadata resources to fetch. E.g. `['organisationUnits', 'attributes']` or like `'dataSets'` if you only want a single type of resource. See `getResources` to see the types of resources available.
1293
- * @param {Object} [params] - Optional `query parameters` e.g. `{filters: ['name:like:ANC'],fields:'*'}`. See `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#metadata-export DHIS2 API docs}
1294
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `getMetadata` operation. Defaults to `{operationName: 'getMetadata', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1295
- * @param {function} [callback] - Optional `callback` to handle the response
1296
- * @returns {Operation}
1297
- * @example <caption>Example getting a list of `data elements` and `indicators` where `name` includes the word **ANC**</caption>
1298
- * getMetadata(['dataElements', 'indicators'], {
1299
- * filters: ['name:like:ANC'],
1300
- * });
1301
- */
1302
-
1303
-
1304
- function getMetadata(resources, params, options, callback) {
1305
- return function (state) {
1306
- var _options$responseType4, _options11, _queryParams, _queryParams2, _options$apiVersion4, _options12, _CONTENT_TYPES$respon4;
1307
-
1308
- resources = (0, _languageCommon.expandReferences)(resources)(state);
1309
- params = (0, _languageCommon.expandReferences)(params)(state);
1310
- options = (0, _languageCommon.expandReferences)(options)(state);
1311
- var operationName = 'getMetadata';
1312
- var _state$configuration6 = state.configuration,
1313
- username = _state$configuration6.username,
1314
- password = _state$configuration6.password,
1315
- hostUrl = _state$configuration6.hostUrl;
1316
- var responseType = (_options$responseType4 = (_options11 = options) === null || _options11 === void 0 ? void 0 : _options11.responseType) !== null && _options$responseType4 !== void 0 ? _options$responseType4 : 'json';
1317
-
1318
- if (typeof resources === 'string') {
1319
- var res = {};
1320
- res[resources] = true;
1321
- resources = res;
1322
- } else {
1323
- resources = resources.reduce(function (acc, currentValue) {
1324
- acc[currentValue] = true;
1325
- return acc;
1326
- }, {});
1327
- }
1328
-
1329
- var queryParams = _objectSpread({}, resources, {}, params);
1330
-
1331
- var filters = (_queryParams = queryParams) === null || _queryParams === void 0 ? void 0 : _queryParams.filters;
1332
- (_queryParams2 = queryParams) === null || _queryParams2 === void 0 ? true : delete _queryParams2.filters;
1333
- queryParams = new URLSearchParams(queryParams);
1334
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1335
- return queryParams.append('filter', f);
1336
- });
1337
- var apiVersion = (_options$apiVersion4 = (_options12 = options) === null || _options12 === void 0 ? void 0 : _options12.apiVersion) !== null && _options$apiVersion4 !== void 0 ? _options$apiVersion4 : state.configuration.apiVersion;
1338
- var headers = {
1339
- Accept: (_CONTENT_TYPES$respon4 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon4 !== void 0 ? _CONTENT_TYPES$respon4 : 'application/json'
1340
- };
1341
- var url = (0, _Utils.buildUrl)('/metadata', hostUrl, apiVersion);
1342
- (0, _Utils.logOperation)(operationName);
1343
- (0, _Utils.logApiVersion)(apiVersion);
1344
- (0, _Utils.logWaitingForServer)(url, queryParams);
1345
- (0, _Utils.warnExpectLargeResult)(queryParams, url);
1346
- return _axios["default"].request({
1347
- method: 'GET',
1348
- url: url,
1349
- auth: {
1350
- username: username,
1351
- password: password
1352
- },
1353
- responseType: responseType,
1354
- params: queryParams,
1355
- headers: headers
1356
- }).then(function (result) {
1357
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your callback."));
1358
-
1359
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1360
- return (0, _languageCommon.composeNextState)(state, result.data);
1361
- });
1362
- };
1363
- }
1364
- /**
1365
- * create data. A generic helper method to create a record of any kind in DHIS2
1366
- * @public
1367
- * @function
1368
- * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`
1369
- * @param {Object} data - Data that will be used to create a given instance of resource
1370
- * @param {Object} [options] - Optional `options` to control the behavior of the `create` operation.` Defaults to `{operationName: 'create', apiVersion: null, responseType: 'json'}`
1371
- * @param {Object} [params] - Optional `import parameters` for a given a resource. 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}. Defauls to `DHIS2 default params` for a given resource type.
1372
- * @param {function} [callback] - Optional callback to handle the response
1373
- * @returns {Operation}
1374
- * @example <caption>- Example `expression.js` of `create`</caption>
1375
- * create('events', {
1376
- * program: 'eBAyeGv0exc',
1377
- * orgUnit: 'DiszpKrYNg8',
1378
- * eventDate: date,
1379
- * status: 'COMPLETED',
1380
- * completedDate: date,
1381
- * storedBy: 'admin',
1382
- * coordinate: {
1383
- * latitude: 59.8,
1384
- * longitude: 10.9,
1385
- * },
1386
- * dataValues: [
1387
- * {
1388
- * dataElement: 'qrur9Dvnyt5',
1389
- * value: '33',
1390
- * },
1391
- * {
1392
- * dataElement: 'oZg33kd9taw',
1393
- * value: 'Male',
1394
- * },
1395
- * {
1396
- * dataElement: 'msodh3rEMJa',
1397
- * value: date,
1398
- * },
1399
- * ],
1400
- * });
1401
- */
1402
-
1403
-
1404
- function create(resourceType, data, options, params, callback) {
1405
- return function (state) {
1406
- var _options$operationNam2, _options13, _options$responseType5, _options14, _params7, _params8, _options$apiVersion5, _options15, _CONTENT_TYPES$respon5;
1407
-
1408
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1409
- var body = (0, _languageCommon.expandReferences)(data)(state);
1410
- options = (0, _languageCommon.expandReferences)(options)(state);
1411
- params = (0, _languageCommon.expandReferences)(params)(state);
1412
- var operationName = (_options$operationNam2 = (_options13 = options) === null || _options13 === void 0 ? void 0 : _options13.operationName) !== null && _options$operationNam2 !== void 0 ? _options$operationNam2 : 'create';
1413
- var _state$configuration7 = state.configuration,
1414
- username = _state$configuration7.username,
1415
- password = _state$configuration7.password,
1416
- hostUrl = _state$configuration7.hostUrl;
1417
- var responseType = (_options$responseType5 = (_options14 = options) === null || _options14 === void 0 ? void 0 : _options14.responseType) !== null && _options$responseType5 !== void 0 ? _options$responseType5 : 'json';
1418
- var filters = (_params7 = params) === null || _params7 === void 0 ? void 0 : _params7.filters;
1419
- (_params8 = params) === null || _params8 === void 0 ? true : delete _params8.filters;
1420
- var queryParams = new URLSearchParams(params);
1421
- var apiVersion = (_options$apiVersion5 = (_options15 = options) === null || _options15 === void 0 ? void 0 : _options15.apiVersion) !== null && _options$apiVersion5 !== void 0 ? _options$apiVersion5 : state.configuration.apiVersion;
1422
- var url = (0, _Utils.buildUrl)('/' + resourceType, hostUrl, apiVersion);
1423
- var headers = {
1424
- Accept: (_CONTENT_TYPES$respon5 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon5 !== void 0 ? _CONTENT_TYPES$respon5 : 'application/json',
1425
- 'Content-Type': 'application/json'
1426
- };
1427
- (0, _Utils.logOperation)(operationName);
1428
- (0, _Utils.logApiVersion)(apiVersion);
1429
- (0, _Utils.logWaitingForServer)(url, queryParams);
1430
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1431
- return _axios["default"].request({
1432
- method: 'POST',
1433
- url: url,
1434
- auth: {
1435
- username: username,
1436
- password: password
1437
- },
1438
- params: queryParams,
1439
- data: body,
1440
- headers: headers
1441
- }).then(function (result) {
1442
- var _result$data$response, _result$data$response2;
1443
-
1444
- _Utils.Log.info("".concat(operationName, " succeeded. Created ").concat(resourceType, ": ").concat(((_result$data$response = result.data.response) === null || _result$data$response === void 0 ? void 0 : _result$data$response.importSummaries) ? result.data.response.importSummaries[0].href : (_result$data$response2 = result.data.response) === null || _result$data$response2 === void 0 ? void 0 : _result$data$response2.reference, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1445
-
1446
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1447
- return (0, _languageCommon.composeNextState)(state, result.data);
1448
- });
1449
- };
1450
- }
1451
- /**
1452
- * Update data. A generic helper function to update a resource object of any type.
1453
- * - It requires to send `all required fields` or the `full body`
1454
- * @public
1455
- * @function
1456
- * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
1457
- * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
1458
- * @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.
1459
- * @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}
1460
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional options for update method. Defaults to `{operationName: 'update', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1461
- * @param {function} [callback] - Optional callback to handle the response
1462
- * @returns {Operation}
1463
- * @example <caption>Example `updating` a `data element`</caption>
1464
- * update('dataElements', 'FTRrcoaog83',
1465
- * {
1466
- * displayName: 'New display name',
1467
- * aggregationType: 'SUM',
1468
- * domainType: 'AGGREGATE',
1469
- * valueType: 'NUMBER',
1470
- * name: 'Accute Flaccid Paralysis (Deaths < 5 yrs)',
1471
- * shortName: 'Accute Flaccid Paral (Deaths < 5 yrs)',
1472
- * });
1473
- *
1474
- */
1475
-
1476
-
1477
- function update(resourceType, path, data, params, options, callback) {
1478
- return function (state) {
1479
- var _options$operationNam3, _options16, _options$responseType6, _options17, _params9, _params10, _options$apiVersion6, _options18, _CONTENT_TYPES$respon6;
1480
-
1481
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1482
- path = (0, _languageCommon.expandReferences)(path)(state);
1483
- var body = (0, _languageCommon.expandReferences)(data)(state);
1484
- params = (0, _languageCommon.expandReferences)(params)(state);
1485
- options = (0, _languageCommon.expandReferences)(options)(state);
1486
- var _state$configuration8 = state.configuration,
1487
- username = _state$configuration8.username,
1488
- password = _state$configuration8.password,
1489
- hostUrl = _state$configuration8.hostUrl;
1490
- var operationName = (_options$operationNam3 = (_options16 = options) === null || _options16 === void 0 ? void 0 : _options16.operationName) !== null && _options$operationNam3 !== void 0 ? _options$operationNam3 : 'update';
1491
- var responseType = (_options$responseType6 = (_options17 = options) === null || _options17 === void 0 ? void 0 : _options17.responseType) !== null && _options$responseType6 !== void 0 ? _options$responseType6 : 'json';
1492
- var filters = (_params9 = params) === null || _params9 === void 0 ? void 0 : _params9.filters;
1493
- (_params10 = params) === null || _params10 === void 0 ? true : delete _params10.filters;
1494
- var queryParams = new URLSearchParams(params);
1495
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1496
- return queryParams.append('filter', f);
1497
- });
1498
- var apiVersion = (_options$apiVersion6 = (_options18 = options) === null || _options18 === void 0 ? void 0 : _options18.apiVersion) !== null && _options$apiVersion6 !== void 0 ? _options$apiVersion6 : state.configuration.apiVersion;
1499
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1500
- var headers = {
1501
- Accept: (_CONTENT_TYPES$respon6 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon6 !== void 0 ? _CONTENT_TYPES$respon6 : 'application/json'
1502
- };
1503
- (0, _Utils.logOperation)(operationName);
1504
- (0, _Utils.logApiVersion)(apiVersion);
1505
- (0, _Utils.logWaitingForServer)(url, queryParams);
1506
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1507
- return _axios["default"].request({
1508
- method: 'PUT',
1509
- url: url,
1510
- auth: {
1511
- username: username,
1512
- password: password
1513
- },
1514
- params: queryParams,
1515
- data: body,
1516
- headers: headers
1517
- }).then(function (result) {
1518
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1519
-
1520
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1521
- return (0, _languageCommon.composeNextState)(state, result.data);
1522
641
  });
1523
642
  };
1524
643
  }
@@ -1541,56 +660,52 @@ function update(resourceType, path, data, params, options, callback) {
1541
660
  * name: 'New Name',
1542
661
  * });
1543
662
  */
663
+ // TODO: @Elias, can this be deleted in favor of update? How does DHIS2 handle PATCH vs PUT?
1544
664
 
1545
665
 
1546
666
  function patch(resourceType, path, data, params, options, callback) {
1547
- return function (state) {
1548
- var _options$operationNam4, _options19, _options$responseType7, _options20, _queryParams3, _queryParams4, _options$apiVersion7, _options21, _CONTENT_TYPES$respon7;
667
+ return state => {
668
+ var _options$operationNam, _options, _options$responseType, _options2, _queryParams, _queryParams2, _options$apiVersion, _options3, _CONTENT_TYPES$respon;
1549
669
 
1550
670
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1551
671
  path = (0, _languageCommon.expandReferences)(path)(state);
1552
- var body = (0, _languageCommon.expandReferences)(data)(state);
672
+ const body = (0, _languageCommon.expandReferences)(data)(state);
1553
673
  params = (0, _languageCommon.expandReferences)(params)(state);
1554
674
  options = (0, _languageCommon.expandReferences)(options)(state);
1555
- var operationName = (_options$operationNam4 = (_options19 = options) === null || _options19 === void 0 ? void 0 : _options19.operationName) !== null && _options$operationNam4 !== void 0 ? _options$operationNam4 : 'patch';
1556
- var _state$configuration9 = state.configuration,
1557
- username = _state$configuration9.username,
1558
- password = _state$configuration9.password,
1559
- hostUrl = _state$configuration9.hostUrl;
1560
- var responseType = (_options$responseType7 = (_options20 = options) === null || _options20 === void 0 ? void 0 : _options20.responseType) !== null && _options$responseType7 !== void 0 ? _options$responseType7 : 'json';
1561
- var queryParams = params;
1562
- var filters = (_queryParams3 = queryParams) === null || _queryParams3 === void 0 ? void 0 : _queryParams3.filters;
1563
- (_queryParams4 = queryParams) === null || _queryParams4 === void 0 ? true : delete _queryParams4.filters;
675
+ const operationName = (_options$operationNam = (_options = options) === null || _options === void 0 ? void 0 : _options.operationName) !== null && _options$operationNam !== void 0 ? _options$operationNam : 'patch';
676
+ 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;
1564
685
  queryParams = new URLSearchParams(queryParams);
1565
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1566
- return queryParams.append('filter', f);
1567
- });
1568
- var apiVersion = (_options$apiVersion7 = (_options21 = options) === null || _options21 === void 0 ? void 0 : _options21.apiVersion) !== null && _options$apiVersion7 !== void 0 ? _options$apiVersion7 : state.configuration.apiVersion;
1569
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1570
- var headers = {
1571
- Accept: (_CONTENT_TYPES$respon7 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon7 !== void 0 ? _CONTENT_TYPES$respon7 : 'application/json'
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'
1572
691
  };
1573
- (0, _Utils.logOperation)(operationName);
1574
- (0, _Utils.logApiVersion)(apiVersion);
1575
- (0, _Utils.logWaitingForServer)(url, queryParams);
1576
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1577
- return _axios["default"].request({
692
+ return _axios.default.request({
1578
693
  method: 'PATCH',
1579
- url: url,
694
+ url,
1580
695
  auth: {
1581
- username: username,
1582
- password: password
696
+ username,
697
+ password
1583
698
  },
1584
699
  params: queryParams,
1585
700
  data: body,
1586
- headers: headers
1587
- }).then(function (result) {
1588
- var resultObject = {
701
+ headers
702
+ }).then(result => {
703
+ let resultObject = {
1589
704
  status: result.status,
1590
705
  statusText: result.statusText
1591
706
  };
1592
707
 
1593
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(resultObject)));
708
+ _Utils.Log.success(`${operationName} succeeded. Updated ${resourceType}.\nSummary:\n${(0, _Utils.prettyJson)(resultObject)}`);
1594
709
 
1595
710
  if (callback) return callback((0, _languageCommon.composeNextState)(state, resultObject));
1596
711
  return (0, _languageCommon.composeNextState)(state, resultObject);
@@ -1611,51 +726,47 @@ function patch(resourceType, path, data, params, options, callback) {
1611
726
  * @example <caption>Example`deleting` a `tracked entity instance`</caption>
1612
727
  * del('trackedEntityInstances', 'LcRd6Nyaq7T');
1613
728
  */
729
+ // TODO: @Elias, can this be implemented using the same pattern as update but without data?
1614
730
 
1615
731
 
1616
732
  function del(resourceType, path, data, params, options, callback) {
1617
- return function (state) {
1618
- var _options$operationNam5, _options22, _options$responseType8, _options23, _queryParams5, _queryParams6, _options$apiVersion8, _options24, _CONTENT_TYPES$respon8;
733
+ return state => {
734
+ var _options$operationNam2, _options4, _options$responseType2, _options5, _queryParams3, _queryParams4, _options$apiVersion2, _options6, _CONTENT_TYPES$respon2;
1619
735
 
1620
736
  resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1621
737
  path = (0, _languageCommon.expandReferences)(path)(state);
1622
- var body = (0, _languageCommon.expandReferences)(data)(state);
738
+ const body = (0, _languageCommon.expandReferences)(data)(state);
1623
739
  params = (0, _languageCommon.expandReferences)(params)(state);
1624
740
  options = (0, _languageCommon.expandReferences)(options)(state);
1625
- var operationName = (_options$operationNam5 = (_options22 = options) === null || _options22 === void 0 ? void 0 : _options22.operationName) !== null && _options$operationNam5 !== void 0 ? _options$operationNam5 : 'delete';
1626
- var _state$configuration10 = state.configuration,
1627
- username = _state$configuration10.username,
1628
- password = _state$configuration10.password,
1629
- hostUrl = _state$configuration10.hostUrl;
1630
- var responseType = (_options$responseType8 = (_options23 = options) === null || _options23 === void 0 ? void 0 : _options23.responseType) !== null && _options$responseType8 !== void 0 ? _options$responseType8 : 'json';
1631
- var queryParams = params;
1632
- var filters = (_queryParams5 = queryParams) === null || _queryParams5 === void 0 ? void 0 : _queryParams5.filters;
1633
- (_queryParams6 = queryParams) === null || _queryParams6 === void 0 ? true : delete _queryParams6.filters;
741
+ const operationName = (_options$operationNam2 = (_options4 = options) === null || _options4 === void 0 ? void 0 : _options4.operationName) !== null && _options$operationNam2 !== void 0 ? _options$operationNam2 : 'delete';
742
+ 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;
1634
751
  queryParams = new URLSearchParams(queryParams);
1635
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1636
- return queryParams.append('filter', f);
1637
- });
1638
- var apiVersion = (_options$apiVersion8 = (_options24 = options) === null || _options24 === void 0 ? void 0 : _options24.apiVersion) !== null && _options$apiVersion8 !== void 0 ? _options$apiVersion8 : state.configuration.apiVersion;
1639
- var headers = {
1640
- Accept: (_CONTENT_TYPES$respon8 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon8 !== void 0 ? _CONTENT_TYPES$respon8 : 'application/json'
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'
1641
756
  };
1642
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1643
- (0, _Utils.logOperation)(operationName);
1644
- (0, _Utils.logApiVersion)(apiVersion);
1645
- (0, _Utils.logWaitingForServer)(url, queryParams);
1646
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1647
- return _axios["default"].request({
757
+ const url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
758
+ return _axios.default.request({
1648
759
  method: 'DELETE',
1649
- url: url,
760
+ url,
1650
761
  auth: {
1651
- username: username,
1652
- password: password
762
+ username,
763
+ password
1653
764
  },
1654
765
  params: queryParams,
1655
766
  data: body,
1656
- headers: headers
1657
- }).then(function (result) {
1658
- _Utils.Log.info("".concat(operationName, " succeeded. DELETED ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
767
+ headers
768
+ }).then(result => {
769
+ _Utils.Log.success(`${operationName} succeeded. DELETED ${resourceType}.\nSummary:\n${(0, _Utils.prettyJson)(result.data)}`);
1659
770
 
1660
771
  if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1661
772
  return (0, _languageCommon.composeNextState)(state, result.data);
@@ -1663,192 +774,37 @@ function del(resourceType, path, data, params, options, callback) {
1663
774
  };
1664
775
  }
1665
776
  /**
1666
- * 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.
777
+ * Gets an attribute value by its case-insensitive display name
1667
778
  * @public
779
+ * @example
780
+ * attrVal(tei.attributes, 'first name')
1668
781
  * @function
1669
- * @param {string} resourceType - The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`
1670
- * @param {{attributeId: string,attributeValue:any}} uniqueAttribute - An object containing a `attributeId` and `attributeValue` which will be used to uniquely identify the record
1671
- * @param {Object} data - The update data containing new values
1672
- * @param {Object} [params] - Optional `import` parameters e.g. `{ou: 'lZGmxYbs97q', filters: ['w75KJ2mc4zz:EQ:Jane']}`
1673
- * @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'}`.
1674
- * @param {function} [callback] - Optional callback to handle the response
1675
- * @throws {RangeError} - Throws range error
1676
- * @returns {Operation}
1677
- * @example <caption>- Example `expression.js` of upsert</caption>
1678
- * upsert(
1679
- * 'trackedEntityInstances',
1680
- * {
1681
- * attributeId: 'lZGmxYbs97q',
1682
- * attributeValue: state =>
1683
- * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
1684
- * .value,
1685
- * },
1686
- * state.data,
1687
- * { ou: 'TSyzvBiovKh' }
1688
- * );
1689
- * @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}
1690
- * @todo Test implementation for upserting metadata
1691
- * @todo Test implementation for upserting data values
1692
- * @todo Implement the updateCondition
782
+ * @param {Object} tei - A tracked entity instance (TEI) object
783
+ * @param {string} attributeName - The 'displayName' to search for in the TEI's attributes
784
+ * @returns {string}
1693
785
  */
1694
786
 
1695
787
 
1696
- function upsert(resourceType, uniqueAttribute, data, params, options, callback) {
1697
- return function (state) {
1698
- var _options$operationNam6, _options25, _options$replace, _options26, _options$responseType9, _options27, _params11, _options$apiVersion9, _options28, _CONTENT_TYPES$respon9;
1699
-
1700
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1701
- uniqueAttribute = (0, _languageCommon.expandReferences)(uniqueAttribute)(state);
1702
- var body = (0, _languageCommon.expandReferences)(data)(state);
1703
- params = (0, _languageCommon.expandReferences)(params)(state);
1704
- options = (0, _languageCommon.expandReferences)(options)(state);
1705
- var operationName = (_options$operationNam6 = (_options25 = options) === null || _options25 === void 0 ? void 0 : _options25.operationName) !== null && _options$operationNam6 !== void 0 ? _options$operationNam6 : 'upsert';
1706
- var _state$configuration11 = state.configuration,
1707
- username = _state$configuration11.username,
1708
- password = _state$configuration11.password,
1709
- hostUrl = _state$configuration11.hostUrl;
1710
- var replace = (_options$replace = (_options26 = options) === null || _options26 === void 0 ? void 0 : _options26.replace) !== null && _options$replace !== void 0 ? _options$replace : false;
1711
- var responseType = (_options$responseType9 = (_options27 = options) === null || _options27 === void 0 ? void 0 : _options27.responseType) !== null && _options$responseType9 !== void 0 ? _options$responseType9 : 'json';
1712
- var _uniqueAttribute = uniqueAttribute,
1713
- attributeId = _uniqueAttribute.attributeId,
1714
- attributeValue = _uniqueAttribute.attributeValue;
1715
- var filters = (_params11 = params) === null || _params11 === void 0 ? void 0 : _params11.filters;
1716
- delete params.filters;
1717
- var queryParams = new URLSearchParams(params);
1718
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1719
- return queryParams.append('filter', f);
1720
- });
1721
- var op = resourceType === 'trackedEntityInstances' ? 'EQ' : 'eq';
1722
- queryParams.append('filter', "".concat(attributeId, ":").concat(op, ":").concat(attributeValue));
1723
- var apiVersion = (_options$apiVersion9 = (_options28 = options) === null || _options28 === void 0 ? void 0 : _options28.apiVersion) !== null && _options$apiVersion9 !== void 0 ? _options$apiVersion9 : state.configuration.apiVersion;
1724
- var url = (0, _Utils.buildUrl)('/' + resourceType, hostUrl, apiVersion);
1725
- var headers = {
1726
- Accept: (_CONTENT_TYPES$respon9 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon9 !== void 0 ? _CONTENT_TYPES$respon9 : 'application/json'
1727
- };
1728
- (0, _Utils.logOperation)(operationName);
1729
- (0, _Utils.logApiVersion)(apiVersion);
1730
- (0, _Utils.logWaitingForServer)(url, queryParams);
1731
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1732
-
1733
- var getResouceName = function getResouceName() {
1734
- return _axios["default"].get(hostUrl + '/api/resources', {
1735
- auth: {
1736
- username: username,
1737
- password: password
1738
- },
1739
- transformResponse: [function (data, headers) {
1740
- var filter = "plural:eq:".concat(resourceType);
1741
-
1742
- if (filter) {
1743
- var _headers$contentType3, _headers$contentType4;
1744
-
1745
- if (((_headers$contentType3 = (_headers$contentType4 = headers['content-type']) === null || _headers$contentType4 === void 0 ? void 0 : _headers$contentType4.split(';')[0]) !== null && _headers$contentType3 !== void 0 ? _headers$contentType3 : null) === _Utils.CONTENT_TYPES.json) {
1746
- var tempData = JSON.parse(data);
1747
- return _objectSpread({}, tempData, {
1748
- resources: _Utils.applyFilter.apply(void 0, [tempData.resources].concat(_toConsumableArray((0, _Utils.parseFilter)(filter))))
1749
- });
1750
- } else {
1751
- _Utils.Log.warn('Filters on this resource are only supported for json content types. Skipping filtering ...');
1752
- }
1753
- }
1754
-
1755
- return data;
1756
- }]
1757
- }).then(function (result) {
1758
- return result.data.resources[0].singular;
1759
- });
1760
- };
1761
-
1762
- var findRecordsWithValueOnAttribute = function findRecordsWithValueOnAttribute() {
1763
- console.log(queryParams);
1764
- return _axios["default"].request({
1765
- method: 'GET',
1766
- url: url,
1767
- auth: {
1768
- username: username,
1769
- password: password
1770
- },
1771
- params: queryParams,
1772
- headers: headers
1773
- });
1774
- };
1775
-
1776
- _Utils.Log.info("Checking if a record exists that matches this filter: attribute{ id: ".concat(attributeId, ", value: ").concat(attributeValue, " } ..."));
1777
-
1778
- return Promise.all([getResouceName(), findRecordsWithValueOnAttribute()]).then(function (_ref3) {
1779
- var _ref4 = _slicedToArray(_ref3, 2),
1780
- resourceName = _ref4[0],
1781
- recordsWithValue = _ref4[1];
1782
-
1783
- var recordsWithValueCount = recordsWithValue.data[resourceType].length;
1784
-
1785
- if (recordsWithValueCount > 1) {
1786
- _Utils.Log.error('');
1787
-
1788
- throw new RangeError("Cannot upsert on Non-unique attribute. The operation found more than one records with the same value of ".concat(attributeValue, " for ").concat(attributeId));
1789
- } else if (recordsWithValueCount === 1) {
1790
- var _row1$id;
788
+ function attrVal(tei, attributeName) {
789
+ var _tei$attributes, _tei$attributes$find;
1791
790
 
1792
- // TODO
1793
- // Log.info(
1794
- // `Unique record found, proceeding to checking if attribute is NULLABLE ...`
1795
- // );
1796
- // if (recordsWithNulls.data[resourceType].length > 0) {
1797
- // throw new Error(
1798
- // `Cannot upsert on Nullable attribute. The operation found records with a NULL value on ${attributeId}.`
1799
- // );
1800
- // }
1801
- _Utils.Log.info("Attribute has unique values. Proceeding to ".concat(replace ? 'replace' : 'merge', " ..."));
1802
-
1803
- var row1 = recordsWithValue.data[resourceType][0];
1804
- var useCustomPATCH = ['trackedEntityInstances'].includes(resourceType) ? true : false;
1805
- var method = replace ? 'PUT' : useCustomPATCH === true ? 'PUT' : 'PATCH';
1806
- var id = (_row1$id = row1['id']) !== null && _row1$id !== void 0 ? _row1$id : row1[resourceName];
1807
- var updateUrl = "".concat(url, "/").concat(id);
1808
- var payload = useCustomPATCH ? _objectSpread({}, row1, {}, body, {
1809
- attributes: [].concat(_toConsumableArray(row1.attributes), _toConsumableArray(body.attributes))
1810
- }) : body;
1811
- return _axios["default"].request({
1812
- method: method,
1813
- url: updateUrl,
1814
- auth: {
1815
- username: username,
1816
- password: password
1817
- },
1818
- data: payload,
1819
- params: queryParams,
1820
- headers: headers
1821
- }).then(function (result) {
1822
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceName, ": ").concat(updateUrl, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1823
-
1824
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1825
- return (0, _languageCommon.composeNextState)(state, result.data);
1826
- });
1827
- } else if (recordsWithValueCount === 0) {
1828
- _Utils.Log.info("Existing record not found, proceeding to CREATE(POST) ..."); // We must delete the filter and ou params so the POST request is not interpreted as a GET request by the server
1829
-
1830
-
1831
- queryParams["delete"]('filter');
1832
- queryParams["delete"]('ou');
1833
- return _axios["default"].request({
1834
- method: 'POST',
1835
- url: url,
1836
- auth: {
1837
- username: username,
1838
- password: password
1839
- },
1840
- data: body,
1841
- params: queryParams,
1842
- headers: headers
1843
- }).then(function (result) {
1844
- var _result$data$response3;
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;
792
+ }
793
+ /**
794
+ * Converts an attribute ID and value into a DSHI2 attribute object
795
+ * @public
796
+ * @example
797
+ * attribute('w75KJ2mc4zz', 'Elias')
798
+ * @function
799
+ * @param {string} attributeId - A tracked entity instance (TEI) attribute ID.
800
+ * @param {string} attributeValue - The value for that attribute.
801
+ * @returns {object}
802
+ */
1845
803
 
1846
- _Utils.Log.info("".concat(operationName, " succeeded. Created ").concat(resourceName, ": ").concat(result.data.response.importSummaries ? result.data.response.importSummaries[0].href : (_result$data$response3 = result.data.response) === null || _result$data$response3 === void 0 ? void 0 : _result$data$response3.reference, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1847
804
 
1848
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1849
- return (0, _languageCommon.composeNextState)(state, result.data);
1850
- });
1851
- }
1852
- });
805
+ function attribute(attributeId, attributeValue) {
806
+ return {
807
+ attribute: attributeId,
808
+ value: attributeValue
1853
809
  };
1854
810
  }