@openfn/language-dhis2 3.0.0-0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Client.js CHANGED
@@ -9,19 +9,35 @@ var _axios = _interopRequireDefault(require("axios"));
9
9
 
10
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
11
 
12
+ /**
13
+ * The request client takes configuration from state and an axios request object
14
+ * then (1) logs the method and URL, (2) applies standard headers and auth
15
+ * before spreading the rest of the axios configuration, and (3) executes an
16
+ * axios request.
17
+ * @function
18
+ * @param {object} configuration - configuration must have a username and password
19
+ * @param {object} axiosRequest - the axiosRequest contains valid axios params: https://axios-http.com/docs/req_config
20
+ * @returns {Promise} a promise that will resolve to either a response object or an error object.
21
+ */
12
22
  function request({
13
23
  username,
14
24
  password
15
25
  }, axiosRequest) {
16
26
  const {
17
27
  method,
18
- url
28
+ url,
29
+ params
19
30
  } = axiosRequest;
20
31
  console.log(`Sending ${method} request to ${url}`);
21
- return _axios.default.request({
32
+ if (params) console.log(` with params:`, params); // NOTE: We don't follow redirects for unsafe methods: https://github.com/axios/axios/issues/2460
33
+
34
+ const safeRedirect = ['get', 'head', 'options', 'trace'].includes(method.toLowerCase());
35
+ return (0, _axios.default)({
22
36
  headers: {
23
37
  'Content-Type': 'application/json'
24
38
  },
39
+ responseType: 'json',
40
+ maxRedirects: safeRedirect ? 5 : 0,
25
41
  auth: {
26
42
  username,
27
43
  password
package/lib/Utils.js CHANGED
@@ -4,21 +4,15 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.buildUrl = buildUrl;
7
+ exports.selectId = selectId;
7
8
  exports.handleResponse = handleResponse;
8
9
  exports.prettyJson = prettyJson;
9
10
  exports.nestArray = nestArray;
10
11
  exports.generateUrl = generateUrl;
11
- exports.buildUrlParams = buildUrlParams;
12
12
  exports.Log = exports.CONTENT_TYPES = void 0;
13
13
 
14
- var _axios = _interopRequireDefault(require("axios"));
15
-
16
- var _lodash = require("lodash");
17
-
18
14
  var _languageCommon = require("@openfn/language-common");
19
15
 
20
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
-
22
16
  const CONTENT_TYPES = {
23
17
  xml: 'application/xml',
24
18
  json: 'application/json',
@@ -30,99 +24,57 @@ exports.CONTENT_TYPES = CONTENT_TYPES;
30
24
 
31
25
  class Log {
32
26
  static success(message) {
33
- return console.info(`✓ ${message} @ ${new Date()}`);
27
+ return console.info(`✓ Success at ${new Date()}:\n`, message);
34
28
  }
35
29
 
36
30
  static warn(message) {
37
- return console.warn(`⚠ Warning: ${message} @ ${new Date()}`);
31
+ return console.warn(`⚠ Warning at ${new Date()}:\n`, message);
38
32
  }
39
33
 
40
34
  static error(message) {
41
- return console.error(`✗ Error: ${message} @ ${new Date()}`);
35
+ return console.error(`✗ Error at ${new Date()}:\n`, message);
42
36
  }
43
37
 
44
38
  }
45
39
 
46
40
  exports.Log = Log;
47
41
 
48
- function buildUrl(path, hostUrl, apiVersion) {
49
- const pathSuffix = apiVersion ? `/${apiVersion}${path}` : `${path}`;
42
+ function buildUrl(urlString, hostUrl, apiVersion) {
43
+ const pathSuffix = apiVersion ? `/${apiVersion}${urlString}` : `${urlString}`;
50
44
  return hostUrl + '/api' + pathSuffix;
51
45
  }
46
+ /**
47
+ * Determines the attribute name for a DHIS2 system ID given a resource type.
48
+ * @param {string} resourceType
49
+ * @returns {string}
50
+ */
51
+
52
+
53
+ function selectId(resourceType) {
54
+ switch (resourceType) {
55
+ case 'trackedEntityInstances':
56
+ return 'trackedEntityInstance';
57
+ // We can extend here if we find other special kinds of resourceType
58
+ // case 'other-special-case':
59
+ // return 'other-special-id';
60
+
61
+ default:
62
+ return 'id';
63
+ }
64
+ } // Write a unit test for this one
65
+
52
66
 
53
67
  function handleResponse(result, state, callback) {
54
- // TODO: @Elias, should composeNextState get passed result OR result.data?
55
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
56
- return (0, _languageCommon.composeNextState)(state, result.data);
68
+ const {
69
+ data
70
+ } = result;
71
+ if (callback) return callback((0, _languageCommon.composeNextState)(state, data));
72
+ return (0, _languageCommon.composeNextState)(state, data);
57
73
  }
58
74
 
59
75
  function prettyJson(data) {
60
76
  return JSON.stringify(data, null, 2);
61
- } // =============================================================================
62
- // TODO: @Elias... what are these functions doing and do they have a place in the new implementation?
63
- // export function getIndicesOf(string, regex) {
64
- // var match,
65
- // indexes = {};
66
- // regex = new RegExp(regex);
67
- // while ((match = regex.exec(string))) {
68
- // let schemaRef;
69
- // if (!indexes[match[0]]) {
70
- // indexes[match[0]] = {};
71
- // }
72
- // let hrefString = string.slice(
73
- // match.index,
74
- // indexOf(string, '}', match.index) - 1
75
- // );
76
- // let lastIndex = lastIndexOf(hrefString, '/') + 1;
77
- // schemaRef = trim(hrefString.slice(lastIndex));
78
- // indexes[match[0]][match.index] = schemaRef;
79
- // }
80
- // return indexes;
81
- // }
82
- // export function isLike(string, words) {
83
- // const wordsArrary = words?.match(/([^\W]+[^\s,]*)/)?.splice(0, 1);
84
- // const isFound = word => RegExp(word, 'i')?.test(string);
85
- // return some(wordsArrary, isFound);
86
- // }
87
- // export const dhis2OperatorMap = {
88
- // eq: eq,
89
- // like: isLike,
90
- // };
91
- // export function applyFilter(
92
- // arrObject,
93
- // targetProperty,
94
- // operator,
95
- // valueToCompareWith
96
- // ) {
97
- // if (targetProperty && operator && valueToCompareWith) {
98
- // try {
99
- // return filter(arrObject, obj =>
100
- // Reflect.apply(operator, obj, [obj[targetProperty], valueToCompareWith])
101
- // );
102
- // } catch (error) {
103
- // Log.warn(
104
- // `Returned unfiltered data. Failed to apply custom filter(${prettyJson({
105
- // targetProperty: targetProperty ?? null,
106
- // operator: operator ?? null,
107
- // value: valueToCompareWith ?? null,
108
- // })}) on this collection. The operator you supplied maybe unsupported on this resource at the moment.`
109
- // );
110
- // return arrObject;
111
- // }
112
- // }
113
- // console.log('No filters applied; returned all records for this resource.');
114
- // return arrObject;
115
- // }
116
- // export function parseFilter(filterExpression) {
117
- // const filterTokens = filterExpression?.split(':');
118
- // filterTokens
119
- // ? (filterTokens[1] = dhis2OperatorMap[filterTokens[1] ?? null])
120
- // : null;
121
- // return filterTokens;
122
- // }
123
- // // TODO: @Elias, end of the investigation block!
124
- // =============================================================================
125
-
77
+ }
126
78
 
127
79
  const isArray = variable => !!variable && variable.constructor === Array;
128
80
 
@@ -132,31 +84,17 @@ function nestArray(data, key) {
132
84
  } : data;
133
85
  }
134
86
 
135
- function generateUrl(configuration, options, resourceType) {
87
+ function generateUrl(configuration, options, resourceType, path = null) {
136
88
  let {
137
89
  hostUrl,
138
90
  apiVersion
139
91
  } = configuration;
140
92
  const urlString = '/' + resourceType; // Note that users can override the apiVersion from configuration with args
141
93
 
142
- if (options === null || options === void 0 ? void 0 : options.apiVersion) apiVersion = options.apiVersion; // TODO: discuss how this actually works on DHIS2. I'm not sure I'm following.
143
-
94
+ if (options === null || options === void 0 ? void 0 : options.apiVersion) apiVersion = options.apiVersion;
144
95
  const apiMessage = apiVersion ? `Using DHIS2 api version ${apiVersion}` : 'Using latest available version of the DHIS2 api on this server.';
145
96
  console.log(apiMessage);
146
- return buildUrl(urlString, hostUrl, apiVersion);
147
- }
148
-
149
- function buildUrlParams(options) {
150
- var _options$params, _options$params2, _options$params3, _options$params4;
151
-
152
- const filters = options === null || options === void 0 ? void 0 : (_options$params = options.params) === null || _options$params === void 0 ? void 0 : _options$params.filters;
153
- const dimensions = options === null || options === void 0 ? void 0 : (_options$params2 = options.params) === null || _options$params2 === void 0 ? void 0 : _options$params2.dimensions; // We remove filters and dimensions before building standard search params.
154
-
155
- options === null || options === void 0 ? true : (_options$params3 = options.params) === null || _options$params3 === void 0 ? true : delete _options$params3.filters;
156
- options === null || options === void 0 ? true : (_options$params4 = options.params) === null || _options$params4 === void 0 ? true : delete _options$params4.dimensions;
157
- const urlParams = new URLSearchParams(options === null || options === void 0 ? void 0 : options.params); // Then we re-apply the filters and dimensions in this dhis2-specific way.
158
-
159
- filters === null || filters === void 0 ? void 0 : filters.map(f => urlParams.append('filter', f));
160
- dimensions === null || dimensions === void 0 ? void 0 : dimensions.map(d => urlParams.append('dimension', d));
161
- return urlParams;
97
+ const url = buildUrl(urlString, hostUrl, apiVersion);
98
+ if (path) return `${url}/${path}`;
99
+ return url;
162
100
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-dhis2",
3
- "version": "3.0.0-0",
3
+ "version": "3.0.0",
4
4
  "description": "DHIS2 Language Pack for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {
@@ -39,7 +39,7 @@
39
39
  "@babel/preset-env": "^7.9.5",
40
40
  "@babel/preset-stage-0": "^7.8.3",
41
41
  "@babel/register": "^7.9.0",
42
- "@openfn/simple-ast": "^0.3.0",
42
+ "@openfn/simple-ast": "^0.4.0",
43
43
  "assertion-error": "^1.0.1",
44
44
  "chai": "^3.4.0",
45
45
  "chai-http": "^4.3.0",