@openfn/language-commcare 1.6.14 → 2.1.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/ast.json CHANGED
@@ -1,5 +1,153 @@
1
1
  {
2
2
  "operations": [
3
+ {
4
+ "name": "get",
5
+ "params": [
6
+ "path",
7
+ "params",
8
+ "callback"
9
+ ],
10
+ "docs": {
11
+ "description": "Make a GET request to any commcare endpoint. The returned objects will be written to state.data.\nA `response` key will be added to state with the HTTP response and a `meta` key",
12
+ "tags": [
13
+ {
14
+ "title": "public",
15
+ "description": null,
16
+ "type": null
17
+ },
18
+ {
19
+ "title": "example",
20
+ "description": "get(\"case\", { limit: 20 })",
21
+ "caption": "Get a list of cases"
22
+ },
23
+ {
24
+ "title": "example",
25
+ "description": "get(\"case/12345\")",
26
+ "caption": "Get a specific case"
27
+ },
28
+ {
29
+ "title": "function",
30
+ "description": null,
31
+ "name": null
32
+ },
33
+ {
34
+ "title": "param",
35
+ "description": "Path to resource",
36
+ "type": {
37
+ "type": "NameExpression",
38
+ "name": "string"
39
+ },
40
+ "name": "path"
41
+ },
42
+ {
43
+ "title": "param",
44
+ "description": "Optional request params such as limit and offset.",
45
+ "type": {
46
+ "type": "NameExpression",
47
+ "name": "RequestQueries"
48
+ },
49
+ "name": "params"
50
+ },
51
+ {
52
+ "title": "param",
53
+ "description": "Optional callback to handle the response",
54
+ "type": {
55
+ "type": "OptionalType",
56
+ "expression": {
57
+ "type": "NameExpression",
58
+ "name": "function"
59
+ }
60
+ },
61
+ "name": "callback"
62
+ },
63
+ {
64
+ "title": "returns",
65
+ "description": null,
66
+ "type": {
67
+ "type": "NameExpression",
68
+ "name": "Operation"
69
+ }
70
+ }
71
+ ]
72
+ },
73
+ "valid": true
74
+ },
75
+ {
76
+ "name": "post",
77
+ "params": [
78
+ "path",
79
+ "data",
80
+ "params",
81
+ "callback"
82
+ ],
83
+ "docs": {
84
+ "description": "Make a post request to commcare",
85
+ "tags": [
86
+ {
87
+ "title": "example",
88
+ "description": "post( \"user\", { \"username\":\"test\", \"password\":\"somepassword\" })"
89
+ },
90
+ {
91
+ "title": "function",
92
+ "description": null,
93
+ "name": null
94
+ },
95
+ {
96
+ "title": "public",
97
+ "description": null,
98
+ "type": null
99
+ },
100
+ {
101
+ "title": "param",
102
+ "description": "Path to resource",
103
+ "type": {
104
+ "type": "NameExpression",
105
+ "name": "string"
106
+ },
107
+ "name": "path"
108
+ },
109
+ {
110
+ "title": "param",
111
+ "description": "Object or JSON which defines data that will be used to create a given instance of resource",
112
+ "type": {
113
+ "type": "NameExpression",
114
+ "name": "object"
115
+ },
116
+ "name": "data"
117
+ },
118
+ {
119
+ "title": "param",
120
+ "description": "Optional request params.",
121
+ "type": {
122
+ "type": "NameExpression",
123
+ "name": "Object"
124
+ },
125
+ "name": "params"
126
+ },
127
+ {
128
+ "title": "param",
129
+ "description": "Optional callback to handle the response",
130
+ "type": {
131
+ "type": "OptionalType",
132
+ "expression": {
133
+ "type": "NameExpression",
134
+ "name": "function"
135
+ }
136
+ },
137
+ "name": "callback"
138
+ },
139
+ {
140
+ "title": "returns",
141
+ "description": null,
142
+ "type": {
143
+ "type": "NameExpression",
144
+ "name": "Operation"
145
+ }
146
+ }
147
+ ]
148
+ },
149
+ "valid": true
150
+ },
3
151
  {
4
152
  "name": "submitXls",
5
153
  "params": [
@@ -34,10 +182,10 @@
34
182
  },
35
183
  {
36
184
  "title": "param",
37
- "description": "Request params including case type and external id.",
185
+ "description": "Request params including case type.",
38
186
  "type": {
39
187
  "type": "NameExpression",
40
- "name": "Object"
188
+ "name": "RequestOptions"
41
189
  },
42
190
  "name": "params"
43
191
  },
@@ -131,10 +279,10 @@
131
279
  },
132
280
  {
133
281
  "title": "param",
134
- "description": "Query params, incl: limit, offset, and custom report filters.",
282
+ "description": "Query params, incl: limit, offset, and any custom report filters.",
135
283
  "type": {
136
284
  "type": "NameExpression",
137
- "name": "Object"
285
+ "name": "RequestQueries"
138
286
  },
139
287
  "name": "params"
140
288
  },
@@ -11,15 +11,24 @@
11
11
  "https://www.commcarehq.org"
12
12
  ]
13
13
  },
14
- "applicationName": {
15
- "title": "Application Name",
14
+ "domain": {
15
+ "title": "Domain",
16
16
  "type": "string",
17
- "description": "The CommCare application name",
17
+ "description": "The CommCare domain name",
18
18
  "minLength": 1,
19
19
  "examples": [
20
20
  "some-proof-of-concept"
21
21
  ]
22
22
  },
23
+ "apiKey": {
24
+ "title": "API Key",
25
+ "type": "string",
26
+ "description": "The CommCare API Key",
27
+ "minLength": 1,
28
+ "examples": [
29
+ "the-long-uuid-provided-by-commcare-that-authenticates-requests"
30
+ ]
31
+ },
23
32
  "appId": {
24
33
  "title": "App ID",
25
34
  "type": "string",
@@ -53,7 +62,6 @@
53
62
  "additionalProperties": true,
54
63
  "required": [
55
64
  "hostUrl",
56
- "applicationName",
57
- "appId"
65
+ "domain"
58
66
  ]
59
67
  }
package/dist/index.cjs CHANGED
@@ -25,22 +25,24 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
25
25
  // src/index.js
26
26
  var src_exports = {};
27
27
  __export(src_exports, {
28
- alterState: () => import_language_common2.alterState,
29
- arrayToString: () => import_language_common2.arrayToString,
30
- combine: () => import_language_common2.combine,
31
- dataPath: () => import_language_common2.dataPath,
32
- dataValue: () => import_language_common2.dataValue,
28
+ alterState: () => import_language_common3.alterState,
29
+ arrayToString: () => import_language_common3.arrayToString,
30
+ combine: () => import_language_common3.combine,
31
+ dataPath: () => import_language_common3.dataPath,
32
+ dataValue: () => import_language_common3.dataValue,
33
33
  default: () => src_default,
34
- each: () => import_language_common2.each,
34
+ each: () => import_language_common3.each,
35
35
  execute: () => execute,
36
36
  fetchReportData: () => fetchReportData,
37
- field: () => import_language_common2.field,
38
- fields: () => import_language_common2.fields,
39
- fn: () => import_language_common2.fn,
40
- http: () => import_language_common2.http,
41
- lastReferenceValue: () => import_language_common2.lastReferenceValue,
42
- merge: () => import_language_common2.merge,
43
- sourceValue: () => import_language_common2.sourceValue,
37
+ field: () => import_language_common3.field,
38
+ fields: () => import_language_common3.fields,
39
+ fn: () => import_language_common3.fn,
40
+ get: () => get,
41
+ http: () => import_language_common3.http,
42
+ lastReferenceValue: () => import_language_common3.lastReferenceValue,
43
+ merge: () => import_language_common3.merge,
44
+ post: () => post,
45
+ sourceValue: () => import_language_common3.sourceValue,
44
46
  submit: () => submit,
45
47
  submitXls: () => submitXls
46
48
  });
@@ -49,147 +51,208 @@ module.exports = __toCommonJS(src_exports);
49
51
  // src/Adaptor.js
50
52
  var Adaptor_exports = {};
51
53
  __export(Adaptor_exports, {
52
- alterState: () => import_language_common2.alterState,
53
- arrayToString: () => import_language_common2.arrayToString,
54
- combine: () => import_language_common2.combine,
55
- dataPath: () => import_language_common2.dataPath,
56
- dataValue: () => import_language_common2.dataValue,
57
- each: () => import_language_common2.each,
54
+ alterState: () => import_language_common3.alterState,
55
+ arrayToString: () => import_language_common3.arrayToString,
56
+ combine: () => import_language_common3.combine,
57
+ dataPath: () => import_language_common3.dataPath,
58
+ dataValue: () => import_language_common3.dataValue,
59
+ each: () => import_language_common3.each,
58
60
  execute: () => execute,
59
61
  fetchReportData: () => fetchReportData,
60
- field: () => import_language_common2.field,
61
- fields: () => import_language_common2.fields,
62
- fn: () => import_language_common2.fn,
63
- http: () => import_language_common2.http,
64
- lastReferenceValue: () => import_language_common2.lastReferenceValue,
65
- merge: () => import_language_common2.merge,
66
- sourceValue: () => import_language_common2.sourceValue,
62
+ field: () => import_language_common3.field,
63
+ fields: () => import_language_common3.fields,
64
+ fn: () => import_language_common3.fn,
65
+ get: () => get,
66
+ http: () => import_language_common3.http,
67
+ lastReferenceValue: () => import_language_common3.lastReferenceValue,
68
+ merge: () => import_language_common3.merge,
69
+ post: () => post,
70
+ sourceValue: () => import_language_common3.sourceValue,
67
71
  submit: () => submit,
68
72
  submitXls: () => submitXls
69
73
  });
70
- var import_language_common = require("@openfn/language-common");
71
- var import_language_http = __toESM(require("@openfn/language-http"), 1);
72
- var import_superagent = __toESM(require("superagent"), 1);
73
- var import_form_data = __toESM(require("form-data"), 1);
74
+ var import_language_common2 = require("@openfn/language-common");
75
+ var import_util2 = require("@openfn/language-common/util");
76
+ var import_node_buffer = require("buffer");
74
77
  var import_js2xmlparser = __toESM(require("js2xmlparser"), 1);
75
78
  var import_xlsx = __toESM(require("xlsx"), 1);
76
- var import_language_common2 = require("@openfn/language-common");
77
- var { get, post } = import_language_http.default;
79
+
80
+ // src/Utils.js
81
+ var import_language_common = require("@openfn/language-common");
82
+ var import_util = require("@openfn/language-common/util");
83
+ var configureAuth = (auth, headers = {}) => {
84
+ if ("apiKey" in auth) {
85
+ Object.assign(headers, {
86
+ Authorization: `ApiKey ${auth.username}:${auth.apiKey}`
87
+ });
88
+ } else if ("password" in auth) {
89
+ Object.assign(headers, (0, import_util.makeBasicAuthHeader)(auth.username, auth.password));
90
+ } else {
91
+ throw new Error(
92
+ "Invalid authorization credentials. Include an apiKey or password in state.configuration"
93
+ );
94
+ }
95
+ return headers;
96
+ };
97
+ var prepareNextState = (state, response, callback = (s) => s) => {
98
+ const { body, ...responseWithoutBody } = response;
99
+ const nextState = {
100
+ ...(0, import_language_common.composeNextState)(state, body.objects ?? body),
101
+ response: { ...responseWithoutBody, ...{ meta: body.meta } }
102
+ };
103
+ return callback(nextState);
104
+ };
105
+ async function request(configuration, path, opts) {
106
+ const { hostUrl } = configuration;
107
+ const {
108
+ method,
109
+ data,
110
+ params = {},
111
+ headers: customHeaders = {},
112
+ contentType,
113
+ parseAs = "json"
114
+ } = opts;
115
+ const headers = configureAuth(configuration, customHeaders);
116
+ if (contentType) {
117
+ headers["content-type"] = contentType;
118
+ }
119
+ const options = {
120
+ body: data,
121
+ headers,
122
+ query: params,
123
+ parseAs,
124
+ maxRedirections: 1,
125
+ baseUrl: hostUrl
126
+ };
127
+ return (0, import_util.request)(method, path, options).then(import_util.logResponse);
128
+ }
129
+
130
+ // src/Adaptor.js
131
+ var import_language_common3 = require("@openfn/language-common");
78
132
  function execute(...operations) {
79
133
  const initialState = {
80
134
  references: [],
81
135
  data: null
82
136
  };
83
137
  return (state) => {
84
- state.configuration.authType = "basic";
85
- state.configuration.baseUrl = "https://www.commcarehq.org/a/".concat(
86
- state.configuration.applicationName
87
- );
88
- return (0, import_language_common.execute)(...operations)({ ...initialState, ...state });
138
+ return (0, import_language_common2.execute)(...operations)({ ...initialState, ...state });
89
139
  };
90
140
  }
91
- function clientPost({ url, body, username, password }) {
92
- return new Promise((resolve, reject) => {
93
- import_superagent.default.post(url).auth(username, password).set("Content-Type", "application/xml").send(body).end((error, res) => {
94
- if (!!error || !res.ok) {
95
- reject(error);
141
+ function get(path, params = {}, callback = (s) => s) {
142
+ return async (state) => {
143
+ const { domain } = state.configuration;
144
+ const [resolvedPath, resolvedParams] = (0, import_util2.expandReferences)(
145
+ state,
146
+ path,
147
+ params
148
+ );
149
+ try {
150
+ const response = await request(
151
+ state.configuration,
152
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
153
+ {
154
+ method: "GET",
155
+ params: resolvedParams,
156
+ contentType: "application/json"
157
+ }
158
+ );
159
+ return prepareNextState(state, response, callback);
160
+ } catch (e) {
161
+ if (e.statusCode === 404) {
162
+ e.body = { error: `Resource ${path} not found` };
96
163
  }
97
- resolve(res);
98
- });
99
- });
164
+ throw e.body.error ?? e;
165
+ }
166
+ };
167
+ }
168
+ function post(path, data, params = {}, callback = (s) => s) {
169
+ return async (state) => {
170
+ const { domain } = state.configuration;
171
+ const [resolvedPath, resolvedData, resolvedParams] = (0, import_util2.expandReferences)(
172
+ state,
173
+ path,
174
+ data,
175
+ params
176
+ );
177
+ try {
178
+ const response = await request(
179
+ state.configuration,
180
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
181
+ {
182
+ method: "POST",
183
+ data: resolvedData,
184
+ params: resolvedParams,
185
+ contentType: "application/json"
186
+ }
187
+ );
188
+ return prepareNextState(state, response, callback);
189
+ } catch (e) {
190
+ throw e.body.error ?? e;
191
+ }
192
+ };
100
193
  }
101
194
  function submitXls(formData, params) {
102
- return (state) => {
103
- const { applicationName, hostUrl, username, apiKey } = state.configuration;
104
- const json = (0, import_language_common.expandReferences)(formData)(state);
195
+ return async (state) => {
196
+ const { domain } = state.configuration;
197
+ const [json] = (0, import_util2.expandReferences)(state, formData);
105
198
  const { case_type, search_field, create_new_cases } = params;
106
- const url = (hostUrl || "https://www.commcarehq.org").concat(
107
- "/a/",
108
- applicationName,
109
- "/importer/excel/bulk_upload_api/"
110
- );
199
+ const path = `/a/${domain}/importer/excel/bulk_upload_api/`;
111
200
  const workbook = import_xlsx.default.utils.book_new();
112
201
  const worksheet = import_xlsx.default.utils.json_to_sheet(json);
113
202
  const ws_name = "SheetJS";
114
203
  import_xlsx.default.utils.book_append_sheet(workbook, worksheet, ws_name);
115
204
  const buffer = import_xlsx.default.write(workbook, { type: "buffer", bookType: "xls" });
116
- const data = new import_form_data.default();
117
- data.append("file", buffer, { filename: "output.xls" });
205
+ const data = new FormData();
206
+ data.append("file", new import_node_buffer.Blob([buffer]), "output.xls");
118
207
  data.append("case_type", case_type);
119
208
  data.append("search_field", search_field);
120
209
  data.append("create_new_cases", create_new_cases);
121
- console.log("Posting to url: ".concat(url));
122
- return import_language_common.http.post({
123
- url,
124
- data,
125
- headers: {
126
- ...data.getHeaders(),
127
- Authorization: `ApiKey ${username}:${apiKey}`
128
- }
129
- })(state).then((response) => {
130
- return { ...state, data: { body: response.data } };
131
- }).catch((err) => {
132
- throw { ...err, config: {}, request: {} };
133
- });
210
+ try {
211
+ const response = await request(state.configuration, path, {
212
+ method: "POST",
213
+ data
214
+ });
215
+ return prepareNextState(state, response);
216
+ } catch (e) {
217
+ throw e.body ?? e;
218
+ }
134
219
  };
135
220
  }
136
221
  function submit(formData) {
137
- return (state) => {
138
- const jsonBody = (0, import_language_common.expandReferences)(formData)(state);
222
+ return async (state) => {
223
+ const [jsonBody] = (0, import_util2.expandReferences)(state, formData);
139
224
  const body = (0, import_js2xmlparser.default)("data", jsonBody);
140
- const {
141
- applicationName,
142
- username,
143
- password,
144
- appId,
145
- hostUrl
146
- } = state.configuration;
147
- const url = (hostUrl || "https://www.commcarehq.org").concat(
148
- "/a/",
149
- applicationName,
150
- "/receiver/",
151
- appId,
152
- "/"
153
- );
154
- console.log("Posting to url: ".concat(url));
225
+ const { domain, appId } = state.configuration;
226
+ const path = `/a/${domain}/receiver/${appId}/`;
155
227
  console.log("Raw JSON body: ".concat(JSON.stringify(jsonBody)));
156
228
  console.log("X-form submission: ".concat(body));
157
- return clientPost({
158
- url,
159
- body,
160
- username,
161
- password
162
- }).then((response) => {
163
- console.log(`Server repsonded with a ${response.status}:`);
164
- console.log(response);
165
- return { ...state, references: [response, ...state.references] };
229
+ const response = await request(state.configuration, path, {
230
+ method: "POST",
231
+ data: body,
232
+ contentType: "text/xml",
233
+ parseAs: "text"
166
234
  });
235
+ return prepareNextState(state, response);
167
236
  };
168
237
  }
169
238
  function fetchReportData(reportId, params, postUrl) {
170
- return import_language_common.http.get(`api/v0.5/configurablereportdata/${reportId}/`, {
171
- query: function(state) {
172
- console.log(
173
- "getting from url: ".concat(
174
- state.configuration.baseUrl,
175
- `/api/v0.5/configurablereportdata/${reportId}/`
176
- )
177
- );
178
- console.log("with params: ".concat(params));
179
- return params;
180
- },
181
- callback: function(state) {
182
- var reportData = state.response.body;
183
- return post(postUrl, {
184
- body: reportData
185
- })(state).then(function(state2) {
186
- delete state2.response;
187
- console.log("fetchReportData succeeded.");
188
- console.log("Posted to: ".concat(postUrl));
189
- return state2;
190
- });
191
- }
192
- });
239
+ return async (state) => {
240
+ const path = `/a/${state.configuration.domain}/api/v0.5/configurablereportdata/${reportId}/`;
241
+ console.log("with params: ".concat(JSON.stringify(params)));
242
+ const { body: reportData } = await request(state.configuration, path, {
243
+ method: "GET",
244
+ contentType: "application/json"
245
+ });
246
+ await request(state.configuration, postUrl, {
247
+ method: "POST",
248
+ params,
249
+ data: reportData,
250
+ contentType: "application/json"
251
+ });
252
+ console.log("fetchReportData succeeded.");
253
+ console.log("Posted to: ", postUrl);
254
+ return state;
255
+ };
193
256
  }
194
257
 
195
258
  // src/index.js
@@ -207,9 +270,11 @@ var src_default = Adaptor_exports;
207
270
  field,
208
271
  fields,
209
272
  fn,
273
+ get,
210
274
  http,
211
275
  lastReferenceValue,
212
276
  merge,
277
+ post,
213
278
  sourceValue,
214
279
  submit,
215
280
  submitXls
package/dist/index.js CHANGED
@@ -18,23 +18,76 @@ __export(Adaptor_exports, {
18
18
  field: () => field,
19
19
  fields: () => fields,
20
20
  fn: () => fn,
21
- http: () => http2,
21
+ get: () => get,
22
+ http: () => http,
22
23
  lastReferenceValue: () => lastReferenceValue,
23
24
  merge: () => merge,
25
+ post: () => post,
24
26
  sourceValue: () => sourceValue,
25
27
  submit: () => submit,
26
28
  submitXls: () => submitXls
27
29
  });
28
- import {
29
- execute as commonExecute,
30
- http,
31
- expandReferences
32
- } from "@openfn/language-common";
33
- import pkg from "@openfn/language-http";
34
- import request from "superagent";
35
- import FormData from "form-data";
30
+ import { execute as commonExecute } from "@openfn/language-common";
31
+ import { expandReferences } from "@openfn/language-common/util";
32
+ import { Blob } from "buffer";
36
33
  import js2xmlparser from "js2xmlparser";
37
34
  import xlsx from "xlsx";
35
+
36
+ // src/Utils.js
37
+ import { composeNextState } from "@openfn/language-common";
38
+ import {
39
+ request as commonRequest,
40
+ makeBasicAuthHeader,
41
+ logResponse
42
+ } from "@openfn/language-common/util";
43
+ var configureAuth = (auth, headers = {}) => {
44
+ if ("apiKey" in auth) {
45
+ Object.assign(headers, {
46
+ Authorization: `ApiKey ${auth.username}:${auth.apiKey}`
47
+ });
48
+ } else if ("password" in auth) {
49
+ Object.assign(headers, makeBasicAuthHeader(auth.username, auth.password));
50
+ } else {
51
+ throw new Error(
52
+ "Invalid authorization credentials. Include an apiKey or password in state.configuration"
53
+ );
54
+ }
55
+ return headers;
56
+ };
57
+ var prepareNextState = (state, response, callback = (s) => s) => {
58
+ const { body, ...responseWithoutBody } = response;
59
+ const nextState = {
60
+ ...composeNextState(state, body.objects ?? body),
61
+ response: { ...responseWithoutBody, ...{ meta: body.meta } }
62
+ };
63
+ return callback(nextState);
64
+ };
65
+ async function request(configuration, path, opts) {
66
+ const { hostUrl } = configuration;
67
+ const {
68
+ method,
69
+ data,
70
+ params = {},
71
+ headers: customHeaders = {},
72
+ contentType,
73
+ parseAs = "json"
74
+ } = opts;
75
+ const headers = configureAuth(configuration, customHeaders);
76
+ if (contentType) {
77
+ headers["content-type"] = contentType;
78
+ }
79
+ const options = {
80
+ body: data,
81
+ headers,
82
+ query: params,
83
+ parseAs,
84
+ maxRedirections: 1,
85
+ baseUrl: hostUrl
86
+ };
87
+ return commonRequest(method, path, options).then(logResponse);
88
+ }
89
+
90
+ // src/Adaptor.js
38
91
  import {
39
92
  fn,
40
93
  alterState,
@@ -45,127 +98,135 @@ import {
45
98
  each,
46
99
  field,
47
100
  fields,
48
- http as http2,
101
+ http,
49
102
  lastReferenceValue,
50
103
  merge,
51
104
  sourceValue
52
105
  } from "@openfn/language-common";
53
- var { get, post } = pkg;
54
106
  function execute(...operations) {
55
107
  const initialState = {
56
108
  references: [],
57
109
  data: null
58
110
  };
59
111
  return (state) => {
60
- state.configuration.authType = "basic";
61
- state.configuration.baseUrl = "https://www.commcarehq.org/a/".concat(
62
- state.configuration.applicationName
63
- );
64
112
  return commonExecute(...operations)({ ...initialState, ...state });
65
113
  };
66
114
  }
67
- function clientPost({ url, body, username, password }) {
68
- return new Promise((resolve, reject) => {
69
- request.post(url).auth(username, password).set("Content-Type", "application/xml").send(body).end((error, res) => {
70
- if (!!error || !res.ok) {
71
- reject(error);
115
+ function get(path, params = {}, callback = (s) => s) {
116
+ return async (state) => {
117
+ const { domain } = state.configuration;
118
+ const [resolvedPath, resolvedParams] = expandReferences(
119
+ state,
120
+ path,
121
+ params
122
+ );
123
+ try {
124
+ const response = await request(
125
+ state.configuration,
126
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
127
+ {
128
+ method: "GET",
129
+ params: resolvedParams,
130
+ contentType: "application/json"
131
+ }
132
+ );
133
+ return prepareNextState(state, response, callback);
134
+ } catch (e) {
135
+ if (e.statusCode === 404) {
136
+ e.body = { error: `Resource ${path} not found` };
72
137
  }
73
- resolve(res);
74
- });
75
- });
138
+ throw e.body.error ?? e;
139
+ }
140
+ };
141
+ }
142
+ function post(path, data, params = {}, callback = (s) => s) {
143
+ return async (state) => {
144
+ const { domain } = state.configuration;
145
+ const [resolvedPath, resolvedData, resolvedParams] = expandReferences(
146
+ state,
147
+ path,
148
+ data,
149
+ params
150
+ );
151
+ try {
152
+ const response = await request(
153
+ state.configuration,
154
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
155
+ {
156
+ method: "POST",
157
+ data: resolvedData,
158
+ params: resolvedParams,
159
+ contentType: "application/json"
160
+ }
161
+ );
162
+ return prepareNextState(state, response, callback);
163
+ } catch (e) {
164
+ throw e.body.error ?? e;
165
+ }
166
+ };
76
167
  }
77
168
  function submitXls(formData, params) {
78
- return (state) => {
79
- const { applicationName, hostUrl, username, apiKey } = state.configuration;
80
- const json = expandReferences(formData)(state);
169
+ return async (state) => {
170
+ const { domain } = state.configuration;
171
+ const [json] = expandReferences(state, formData);
81
172
  const { case_type, search_field, create_new_cases } = params;
82
- const url = (hostUrl || "https://www.commcarehq.org").concat(
83
- "/a/",
84
- applicationName,
85
- "/importer/excel/bulk_upload_api/"
86
- );
173
+ const path = `/a/${domain}/importer/excel/bulk_upload_api/`;
87
174
  const workbook = xlsx.utils.book_new();
88
175
  const worksheet = xlsx.utils.json_to_sheet(json);
89
176
  const ws_name = "SheetJS";
90
177
  xlsx.utils.book_append_sheet(workbook, worksheet, ws_name);
91
178
  const buffer = xlsx.write(workbook, { type: "buffer", bookType: "xls" });
92
179
  const data = new FormData();
93
- data.append("file", buffer, { filename: "output.xls" });
180
+ data.append("file", new Blob([buffer]), "output.xls");
94
181
  data.append("case_type", case_type);
95
182
  data.append("search_field", search_field);
96
183
  data.append("create_new_cases", create_new_cases);
97
- console.log("Posting to url: ".concat(url));
98
- return http.post({
99
- url,
100
- data,
101
- headers: {
102
- ...data.getHeaders(),
103
- Authorization: `ApiKey ${username}:${apiKey}`
104
- }
105
- })(state).then((response) => {
106
- return { ...state, data: { body: response.data } };
107
- }).catch((err) => {
108
- throw { ...err, config: {}, request: {} };
109
- });
184
+ try {
185
+ const response = await request(state.configuration, path, {
186
+ method: "POST",
187
+ data
188
+ });
189
+ return prepareNextState(state, response);
190
+ } catch (e) {
191
+ throw e.body ?? e;
192
+ }
110
193
  };
111
194
  }
112
195
  function submit(formData) {
113
- return (state) => {
114
- const jsonBody = expandReferences(formData)(state);
196
+ return async (state) => {
197
+ const [jsonBody] = expandReferences(state, formData);
115
198
  const body = js2xmlparser("data", jsonBody);
116
- const {
117
- applicationName,
118
- username,
119
- password,
120
- appId,
121
- hostUrl
122
- } = state.configuration;
123
- const url = (hostUrl || "https://www.commcarehq.org").concat(
124
- "/a/",
125
- applicationName,
126
- "/receiver/",
127
- appId,
128
- "/"
129
- );
130
- console.log("Posting to url: ".concat(url));
199
+ const { domain, appId } = state.configuration;
200
+ const path = `/a/${domain}/receiver/${appId}/`;
131
201
  console.log("Raw JSON body: ".concat(JSON.stringify(jsonBody)));
132
202
  console.log("X-form submission: ".concat(body));
133
- return clientPost({
134
- url,
135
- body,
136
- username,
137
- password
138
- }).then((response) => {
139
- console.log(`Server repsonded with a ${response.status}:`);
140
- console.log(response);
141
- return { ...state, references: [response, ...state.references] };
203
+ const response = await request(state.configuration, path, {
204
+ method: "POST",
205
+ data: body,
206
+ contentType: "text/xml",
207
+ parseAs: "text"
142
208
  });
209
+ return prepareNextState(state, response);
143
210
  };
144
211
  }
145
212
  function fetchReportData(reportId, params, postUrl) {
146
- return http.get(`api/v0.5/configurablereportdata/${reportId}/`, {
147
- query: function(state) {
148
- console.log(
149
- "getting from url: ".concat(
150
- state.configuration.baseUrl,
151
- `/api/v0.5/configurablereportdata/${reportId}/`
152
- )
153
- );
154
- console.log("with params: ".concat(params));
155
- return params;
156
- },
157
- callback: function(state) {
158
- var reportData = state.response.body;
159
- return post(postUrl, {
160
- body: reportData
161
- })(state).then(function(state2) {
162
- delete state2.response;
163
- console.log("fetchReportData succeeded.");
164
- console.log("Posted to: ".concat(postUrl));
165
- return state2;
166
- });
167
- }
168
- });
213
+ return async (state) => {
214
+ const path = `/a/${state.configuration.domain}/api/v0.5/configurablereportdata/${reportId}/`;
215
+ console.log("with params: ".concat(JSON.stringify(params)));
216
+ const { body: reportData } = await request(state.configuration, path, {
217
+ method: "GET",
218
+ contentType: "application/json"
219
+ });
220
+ await request(state.configuration, postUrl, {
221
+ method: "POST",
222
+ params,
223
+ data: reportData,
224
+ contentType: "application/json"
225
+ });
226
+ console.log("fetchReportData succeeded.");
227
+ console.log("Posted to: ", postUrl);
228
+ return state;
229
+ };
169
230
  }
170
231
 
171
232
  // src/index.js
@@ -183,9 +244,11 @@ export {
183
244
  field,
184
245
  fields,
185
246
  fn,
186
- http2 as http,
247
+ get,
248
+ http,
187
249
  lastReferenceValue,
188
250
  merge,
251
+ post,
189
252
  sourceValue,
190
253
  submit,
191
254
  submitXls
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-commcare",
3
- "version": "1.6.14",
3
+ "version": "2.1.0",
4
4
  "description": "Commcare Language Pack for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {
@@ -17,14 +17,12 @@
17
17
  "configuration-schema.json"
18
18
  ],
19
19
  "dependencies": {
20
- "@openfn/language-common": "1.13.3",
21
- "@openfn/language-http": "^6.0.0",
22
20
  "JSONPath": "^0.10.0",
23
- "form-data": "^4.0.0",
24
21
  "js2xmlparser": "^1.0.0",
25
22
  "lodash-fp": "^0.10.4",
26
- "superagent": "^8.0.9",
27
- "xlsx": "https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz"
23
+ "sinon": "^18.0.0",
24
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz",
25
+ "@openfn/language-common": "1.13.5"
28
26
  },
29
27
  "devDependencies": {
30
28
  "@openfn/simple-ast": "^0.4.1",
@@ -1,3 +1,26 @@
1
+ /**
2
+ * Queries provided to the GET request
3
+ * @typedef {Object} RequestQueries
4
+ * @property {number} limit - The maximum number of records to return. Default: 20. Maximum: 5000.
5
+ * @property {number} offset - The number of records to offset in the results. Default: 0
6
+ * @property {string} xmlns - Optional form XML namespace. See the [Commcare Docs](https://dimagi.atlassian.net/wiki/spaces/commcarepublic/pages/2143979045/Finding+a+Form%27s+XMLNS)
7
+ * @property {string} indexed_on_start - Optional date (and time). Will return only forms that have had data modified since the passed in date.
8
+ * @property {string} indexed_on_end - Optional date (and time). Will return only forms that have had data modified before the passed in date.
9
+ * @property {string} received_on_start - Optional date (and time). Will return only forms that were received after the passed in date.
10
+ * @property {string} received_on_end - Optional date (and time). Will return only forms that were received before the passed in date.
11
+ * @property {string} app_id - The returned records will be limited to the application defined
12
+ * @property {string} case_id - A case UUID. Will only return forms which updated that case.
13
+ * @property {string} owner_id - Optional user of group UUID used when getting cases
14
+ * @property {string} user_id - Optional UUID for all cases last modified by that user
15
+ * @property {string} type - Optional case type to get all matching cases
16
+ */
17
+ /**
18
+ * Queries provided to the submitXls request
19
+ * @typedef {Object} RequestOptions
20
+ * @property {string} case_type - Optional case type
21
+ * @property {string} search_field - Optional search field
22
+ * @property {string} create_new_cases - Optional for allowing to create new cases. Default `:on`
23
+ */
1
24
  /**
2
25
  * Execute a sequence of operations.
3
26
  * Wraps `language-common/execute`, and prepends initial state for commcare.
@@ -11,6 +34,34 @@
11
34
  * @returns {Operation}
12
35
  */
13
36
  export function execute(...operations: Operations): Operation;
37
+ /**
38
+ * Make a GET request to any commcare endpoint. The returned objects will be written to state.data.
39
+ * A `response` key will be added to state with the HTTP response and a `meta` key
40
+ * @public
41
+ * @example <caption>Get a list of cases</caption>
42
+ * get("case", { limit: 20 })
43
+ * @example <caption>Get a specific case </caption>
44
+ * get("case/12345")
45
+ * @function
46
+ * @param {string} path - Path to resource
47
+ * @param {RequestQueries} params - Optional request params such as limit and offset.
48
+ * @param {function} [callback] - Optional callback to handle the response
49
+ * @returns {Operation}
50
+ */
51
+ export function get(path: string, params?: RequestQueries, callback?: Function): Operation;
52
+ /**
53
+ * Make a post request to commcare
54
+ * @example
55
+ * post( "user", { "username":"test", "password":"somepassword" })
56
+ * @function
57
+ * @public
58
+ * @param {string} path - Path to resource
59
+ * @param {object} data - Object or JSON which defines data that will be used to create a given instance of resource
60
+ * @param {Object} params - Optional request params.
61
+ * @param {function} [callback] - Optional callback to handle the response
62
+ * @returns {Operation}
63
+ */
64
+ export function post(path: string, data: object, params?: any, callback?: Function): Operation;
14
65
  /**
15
66
  * Convert form data to xls then submit.
16
67
  * @public
@@ -27,10 +78,10 @@ export function execute(...operations: Operations): Operation;
27
78
  * )
28
79
  * @function
29
80
  * @param {Object} formData - Object including form data.
30
- * @param {Object} params - Request params including case type and external id.
81
+ * @param {RequestOptions} params - Request params including case type.
31
82
  * @returns {Operation}
32
83
  */
33
- export function submitXls(formData: any, params: any): Operation;
84
+ export function submitXls(formData: any, params: RequestOptions): Operation;
34
85
  /**
35
86
  * Submit form data
36
87
  * @public
@@ -59,9 +110,79 @@ export function submit(formData: any): Operation;
59
110
  * fetchReportData(reportId, params, postUrl)
60
111
  * @function
61
112
  * @param {String} reportId - API name of the report.
62
- * @param {Object} params - Query params, incl: limit, offset, and custom report filters.
113
+ * @param {RequestQueries} params - Query params, incl: limit, offset, and any custom report filters.
63
114
  * @param {String} postUrl - Url to which the response object will be posted.
64
115
  * @returns {Operation}
65
116
  */
66
- export function fetchReportData(reportId: string, params: any, postUrl: string): Operation;
117
+ export function fetchReportData(reportId: string, params: RequestQueries, postUrl: string): Operation;
118
+ /**
119
+ * Queries provided to the GET request
120
+ */
121
+ export type RequestQueries = {
122
+ /**
123
+ * - The maximum number of records to return. Default: 20. Maximum: 5000.
124
+ */
125
+ limit: number;
126
+ /**
127
+ * - The number of records to offset in the results. Default: 0
128
+ */
129
+ offset: number;
130
+ /**
131
+ * - Optional form XML namespace. See the [Commcare Docs](https://dimagi.atlassian.net/wiki/spaces/commcarepublic/pages/2143979045/Finding+a+Form%27s+XMLNS)
132
+ */
133
+ xmlns: string;
134
+ /**
135
+ * - Optional date (and time). Will return only forms that have had data modified since the passed in date.
136
+ */
137
+ indexed_on_start: string;
138
+ /**
139
+ * - Optional date (and time). Will return only forms that have had data modified before the passed in date.
140
+ */
141
+ indexed_on_end: string;
142
+ /**
143
+ * - Optional date (and time). Will return only forms that were received after the passed in date.
144
+ */
145
+ received_on_start: string;
146
+ /**
147
+ * - Optional date (and time). Will return only forms that were received before the passed in date.
148
+ */
149
+ received_on_end: string;
150
+ /**
151
+ * - The returned records will be limited to the application defined
152
+ */
153
+ app_id: string;
154
+ /**
155
+ * - A case UUID. Will only return forms which updated that case.
156
+ */
157
+ case_id: string;
158
+ /**
159
+ * - Optional user of group UUID used when getting cases
160
+ */
161
+ owner_id: string;
162
+ /**
163
+ * - Optional UUID for all cases last modified by that user
164
+ */
165
+ user_id: string;
166
+ /**
167
+ * - Optional case type to get all matching cases
168
+ */
169
+ type: string;
170
+ };
171
+ /**
172
+ * Queries provided to the submitXls request
173
+ */
174
+ export type RequestOptions = {
175
+ /**
176
+ * - Optional case type
177
+ */
178
+ case_type: string;
179
+ /**
180
+ * - Optional search field
181
+ */
182
+ search_field: string;
183
+ /**
184
+ * - Optional for allowing to create new cases. Default `:on`
185
+ */
186
+ create_new_cases: string;
187
+ };
67
188
  export { fn, alterState, arrayToString, combine, dataPath, dataValue, each, field, fields, http, lastReferenceValue, merge, sourceValue } from "@openfn/language-common";
@@ -0,0 +1,3 @@
1
+ export function request(configuration: any, path: any, opts: any): Promise<any>;
2
+ export function configureAuth(auth: any, headers?: {}): {};
3
+ export function prepareNextState(state: any, response: any, callback?: (s: any) => any): any;