@openfn/language-commcare 1.6.14 → 2.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/ast.json CHANGED
@@ -1,5 +1,72 @@
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\n- The response returned is {meta:{}, objects:[]}. These are destructured where objects will be written into state.data and meta into state.response along with the status code and returned headers.",
12
+ "tags": [
13
+ {
14
+ "title": "public",
15
+ "description": null,
16
+ "type": null
17
+ },
18
+ {
19
+ "title": "example",
20
+ "description": "get(\n \"case\"\n {\n limit: 1,\n offset:0,\n }\n)\n * @example <caption>Get a specific case </caption>\nget(\n \"case/12345\"\n {\n limit: 1,\n offset:0,\n }\n)",
21
+ "caption": "Get a list of cases"
22
+ },
23
+ {
24
+ "title": "function",
25
+ "description": null,
26
+ "name": null
27
+ },
28
+ {
29
+ "title": "param",
30
+ "description": "Path to resource",
31
+ "type": {
32
+ "type": "NameExpression",
33
+ "name": "string"
34
+ },
35
+ "name": "path"
36
+ },
37
+ {
38
+ "title": "param",
39
+ "description": "Optional request params such as limit and offset.",
40
+ "type": {
41
+ "type": "NameExpression",
42
+ "name": "Object"
43
+ },
44
+ "name": "params"
45
+ },
46
+ {
47
+ "title": "param",
48
+ "description": "Optional callback to handle the response",
49
+ "type": {
50
+ "type": "OptionalType",
51
+ "expression": {
52
+ "type": "NameExpression",
53
+ "name": "function"
54
+ }
55
+ },
56
+ "name": "callback"
57
+ },
58
+ {
59
+ "title": "returns",
60
+ "description": null,
61
+ "type": {
62
+ "type": "NameExpression",
63
+ "name": "Operation"
64
+ }
65
+ }
66
+ ]
67
+ },
68
+ "valid": true
69
+ },
3
70
  {
4
71
  "name": "submitXls",
5
72
  "params": [
@@ -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,206 @@ 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
138
+ return (0, import_language_common2.execute)(...operations)({ ...initialState, ...state });
139
+ };
140
+ }
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
87
148
  );
88
- return (0, import_language_common.execute)(...operations)({ ...initialState, ...state });
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
+ throw e.body ?? e;
162
+ }
89
163
  };
90
164
  }
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);
96
- }
97
- resolve(res);
98
- });
99
- });
165
+ function post(path, data, params = {}, callback = (s) => s) {
166
+ return async (state) => {
167
+ const { domain } = state.configuration;
168
+ const [resolvedPath, resolvedData, resolvedParams] = (0, import_util2.expandReferences)(
169
+ state,
170
+ path,
171
+ data,
172
+ params
173
+ );
174
+ try {
175
+ const response = await request(
176
+ state.configuration,
177
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
178
+ {
179
+ method: "POST",
180
+ data: resolvedData,
181
+ params: resolvedParams,
182
+ contentType: "application/json"
183
+ }
184
+ );
185
+ return prepareNextState(state, response, callback);
186
+ } catch (e) {
187
+ throw e.body.error ?? e;
188
+ }
189
+ };
100
190
  }
101
191
  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);
192
+ return async (state) => {
193
+ const { domain } = state.configuration;
194
+ const [json] = (0, import_util2.expandReferences)(state, formData);
105
195
  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
- );
196
+ const path = `/a/${domain}/importer/excel/bulk_upload_api/`;
111
197
  const workbook = import_xlsx.default.utils.book_new();
112
198
  const worksheet = import_xlsx.default.utils.json_to_sheet(json);
113
199
  const ws_name = "SheetJS";
114
200
  import_xlsx.default.utils.book_append_sheet(workbook, worksheet, ws_name);
115
201
  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" });
202
+ const data = new FormData();
203
+ data.append("file", new import_node_buffer.Blob([buffer]), "output.xls");
118
204
  data.append("case_type", case_type);
119
205
  data.append("search_field", search_field);
120
206
  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
- });
207
+ try {
208
+ const response = await request(state.configuration, path, {
209
+ method: "POST",
210
+ data
211
+ });
212
+ return prepareNextState(state, response);
213
+ } catch (e) {
214
+ throw e.body ?? e;
215
+ }
134
216
  };
135
217
  }
136
218
  function submit(formData) {
137
- return (state) => {
138
- const jsonBody = (0, import_language_common.expandReferences)(formData)(state);
219
+ return async (state) => {
220
+ const [jsonBody] = (0, import_util2.expandReferences)(state, formData);
139
221
  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));
222
+ const { domain, appId } = state.configuration;
223
+ const path = `/a/${domain}/receiver/${appId}/`;
155
224
  console.log("Raw JSON body: ".concat(JSON.stringify(jsonBody)));
156
225
  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] };
226
+ const response = await request(state.configuration, path, {
227
+ method: "POST",
228
+ data: body,
229
+ contentType: "text/xml",
230
+ parseAs: "text"
166
231
  });
232
+ return prepareNextState(state, response);
167
233
  };
168
234
  }
169
235
  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
- });
236
+ return async (state) => {
237
+ const path = `/a/${state.configuration.domain}/api/v0.5/configurablereportdata/${reportId}/`;
238
+ console.log("with params: ".concat(JSON.stringify(params)));
239
+ const { body: reportData } = await request(state.configuration, path, {
240
+ method: "GET",
241
+ contentType: "application/json"
242
+ });
243
+ const result = await request(state.configuration, postUrl, {
244
+ method: "POST",
245
+ params,
246
+ data: reportData,
247
+ contentType: "application/json"
248
+ });
249
+ delete result.response;
250
+ console.log("fetchReportData succeeded.");
251
+ console.log("Posted to: ".concat(postUrl));
252
+ return prepareNextState(state, {});
253
+ };
193
254
  }
194
255
 
195
256
  // src/index.js
@@ -207,9 +268,11 @@ var src_default = Adaptor_exports;
207
268
  field,
208
269
  fields,
209
270
  fn,
271
+ get,
210
272
  http,
211
273
  lastReferenceValue,
212
274
  merge,
275
+ post,
213
276
  sourceValue,
214
277
  submit,
215
278
  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,133 @@ 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);
72
- }
73
- resolve(res);
74
- });
75
- });
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
+ throw e.body ?? e;
136
+ }
137
+ };
138
+ }
139
+ function post(path, data, params = {}, callback = (s) => s) {
140
+ return async (state) => {
141
+ const { domain } = state.configuration;
142
+ const [resolvedPath, resolvedData, resolvedParams] = expandReferences(
143
+ state,
144
+ path,
145
+ data,
146
+ params
147
+ );
148
+ try {
149
+ const response = await request(
150
+ state.configuration,
151
+ `/a/${domain}/api/v0.5/${resolvedPath}`,
152
+ {
153
+ method: "POST",
154
+ data: resolvedData,
155
+ params: resolvedParams,
156
+ contentType: "application/json"
157
+ }
158
+ );
159
+ return prepareNextState(state, response, callback);
160
+ } catch (e) {
161
+ throw e.body.error ?? e;
162
+ }
163
+ };
76
164
  }
77
165
  function submitXls(formData, params) {
78
- return (state) => {
79
- const { applicationName, hostUrl, username, apiKey } = state.configuration;
80
- const json = expandReferences(formData)(state);
166
+ return async (state) => {
167
+ const { domain } = state.configuration;
168
+ const [json] = expandReferences(state, formData);
81
169
  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
- );
170
+ const path = `/a/${domain}/importer/excel/bulk_upload_api/`;
87
171
  const workbook = xlsx.utils.book_new();
88
172
  const worksheet = xlsx.utils.json_to_sheet(json);
89
173
  const ws_name = "SheetJS";
90
174
  xlsx.utils.book_append_sheet(workbook, worksheet, ws_name);
91
175
  const buffer = xlsx.write(workbook, { type: "buffer", bookType: "xls" });
92
176
  const data = new FormData();
93
- data.append("file", buffer, { filename: "output.xls" });
177
+ data.append("file", new Blob([buffer]), "output.xls");
94
178
  data.append("case_type", case_type);
95
179
  data.append("search_field", search_field);
96
180
  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
- });
181
+ try {
182
+ const response = await request(state.configuration, path, {
183
+ method: "POST",
184
+ data
185
+ });
186
+ return prepareNextState(state, response);
187
+ } catch (e) {
188
+ throw e.body ?? e;
189
+ }
110
190
  };
111
191
  }
112
192
  function submit(formData) {
113
- return (state) => {
114
- const jsonBody = expandReferences(formData)(state);
193
+ return async (state) => {
194
+ const [jsonBody] = expandReferences(state, formData);
115
195
  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));
196
+ const { domain, appId } = state.configuration;
197
+ const path = `/a/${domain}/receiver/${appId}/`;
131
198
  console.log("Raw JSON body: ".concat(JSON.stringify(jsonBody)));
132
199
  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] };
200
+ const response = await request(state.configuration, path, {
201
+ method: "POST",
202
+ data: body,
203
+ contentType: "text/xml",
204
+ parseAs: "text"
142
205
  });
206
+ return prepareNextState(state, response);
143
207
  };
144
208
  }
145
209
  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
- });
210
+ return async (state) => {
211
+ const path = `/a/${state.configuration.domain}/api/v0.5/configurablereportdata/${reportId}/`;
212
+ console.log("with params: ".concat(JSON.stringify(params)));
213
+ const { body: reportData } = await request(state.configuration, path, {
214
+ method: "GET",
215
+ contentType: "application/json"
216
+ });
217
+ const result = await request(state.configuration, postUrl, {
218
+ method: "POST",
219
+ params,
220
+ data: reportData,
221
+ contentType: "application/json"
222
+ });
223
+ delete result.response;
224
+ console.log("fetchReportData succeeded.");
225
+ console.log("Posted to: ".concat(postUrl));
226
+ return prepareNextState(state, {});
227
+ };
169
228
  }
170
229
 
171
230
  // src/index.js
@@ -183,9 +242,11 @@ export {
183
242
  field,
184
243
  fields,
185
244
  fn,
186
- http2 as http,
245
+ get,
246
+ http,
187
247
  lastReferenceValue,
188
248
  merge,
249
+ post,
189
250
  sourceValue,
190
251
  submit,
191
252
  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.0.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.4"
28
26
  },
29
27
  "devDependencies": {
30
28
  "@openfn/simple-ast": "^0.4.1",
@@ -11,6 +11,49 @@
11
11
  * @returns {Operation}
12
12
  */
13
13
  export function execute(...operations: Operations): Operation;
14
+ /**
15
+ * Make a get request to any commcare endpoint
16
+ * - The response returned is {meta:{}, objects:[]}. These are destructured where objects will be written into state.data and meta into state.response along with the status code and returned headers.
17
+ * @public
18
+ * @example <caption>Get a list of cases</caption>
19
+ * get(
20
+ * "case"
21
+ * {
22
+ * limit: 1,
23
+ * offset:0,
24
+ * }
25
+ * )
26
+ * * @example <caption>Get a specific case </caption>
27
+ * get(
28
+ * "case/12345"
29
+ * {
30
+ * limit: 1,
31
+ * offset:0,
32
+ * }
33
+ * )
34
+ * @function
35
+ * @param {string} path - Path to resource
36
+ * @param {Object} params - Optional request params such as limit and offset.
37
+ * @param {function} [callback] - Optional callback to handle the response
38
+ * @returns {Operation}
39
+ */
40
+ export function get(path: string, params?: any, callback?: Function): Operation;
41
+ /**
42
+ * Make a post request to commcare
43
+ * @example
44
+ * post(
45
+ * "user",
46
+ * {"username":"test",
47
+ * "password":"somepassword"}
48
+ * );
49
+ * @function
50
+ * @param {string} path - Path to resource
51
+ * @param {object} data - Object or JSON which defines data that will be used to create a given instance of resource
52
+ * @param {Object} params - Optional request params.
53
+ * @param {function} [callback] - Optional callback to handle the response
54
+ * @returns {Operation}
55
+ */
56
+ export function post(path: string, data: object, params?: any, callback?: Function): Operation;
14
57
  /**
15
58
  * Convert form data to xls then submit.
16
59
  * @public
@@ -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;