@openfn/language-dhis2 2.0.9 → 3.0.0-2

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