This repository has been archived by the owner on Oct 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Adaptor.js
322 lines (294 loc) · 7.95 KB
/
Adaptor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.execute = execute;
exports.submitXls = submitXls;
exports.submit = submit;
exports.fetchReportData = fetchReportData;
Object.defineProperty(exports, "alterState", {
enumerable: true,
get: function () {
return _languageCommon.alterState;
}
});
Object.defineProperty(exports, "arrayToString", {
enumerable: true,
get: function () {
return _languageCommon.arrayToString;
}
});
Object.defineProperty(exports, "combine", {
enumerable: true,
get: function () {
return _languageCommon.combine;
}
});
Object.defineProperty(exports, "dataPath", {
enumerable: true,
get: function () {
return _languageCommon.dataPath;
}
});
Object.defineProperty(exports, "dataValue", {
enumerable: true,
get: function () {
return _languageCommon.dataValue;
}
});
Object.defineProperty(exports, "each", {
enumerable: true,
get: function () {
return _languageCommon.each;
}
});
Object.defineProperty(exports, "field", {
enumerable: true,
get: function () {
return _languageCommon.field;
}
});
Object.defineProperty(exports, "fields", {
enumerable: true,
get: function () {
return _languageCommon.fields;
}
});
Object.defineProperty(exports, "http", {
enumerable: true,
get: function () {
return _languageCommon.http;
}
});
Object.defineProperty(exports, "lastReferenceValue", {
enumerable: true,
get: function () {
return _languageCommon.lastReferenceValue;
}
});
Object.defineProperty(exports, "merge", {
enumerable: true,
get: function () {
return _languageCommon.merge;
}
});
Object.defineProperty(exports, "sourceValue", {
enumerable: true,
get: function () {
return _languageCommon.sourceValue;
}
});
var _languageCommon = require("@openfn/language-common");
var _superagent = _interopRequireDefault(require("superagent"));
var _formData = _interopRequireDefault(require("form-data"));
var _js2xmlparser = _interopRequireDefault(require("js2xmlparser"));
var _languageHttp = _interopRequireDefault(require("language-http"));
var _xlsx = _interopRequireDefault(require("xlsx"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/** @module Adaptor */
/**
* Execute a sequence of operations.
* Wraps `language-common/execute`, and prepends initial state for commcare.
* @example
* execute(
* create('foo'),
* delete('bar')
* )(state)
* @constructor
* @param {Operations} operations - Operations to be performed.
* @returns {Operation}
*/
function execute(...operations) {
const initialState = {
references: [],
data: null
};
return state => {
state.configuration.authType = 'basic';
state.configuration.baseUrl = 'https://www.commcarehq.org/a/'.concat(state.configuration.applicationName);
return (0, _languageCommon.execute)(...operations)({ ...initialState,
...state
});
};
}
/**
* Performs a post request
* @example
* clientPost(formData)
* @constructor
* @param {Object} formData - Form Data with auth params and body
* @returns {State}
*/
function clientPost({
url,
body,
username,
password
}) {
return new Promise((resolve, reject) => {
_superagent.default.post(url).auth(username, password).set('Content-Type', 'application/xml').send(body).end((error, res) => {
if (!!error || !res.ok) {
reject(error);
}
resolve(res);
});
});
}
/**
* Convert form data to xls then submit.
* @public
* @example
* submitXls(
* [
* {name: 'Mamadou', phone: '000000'},
* ],
* {
* case_type: 'student',
* search_field: 'external_id',
* create_new_cases: 'on',
* }
* )
* @constructor
* @param {Object} formData - Object including form data.
* @param {Object} params - Request params including case type and external id.
* @returns {Operation}
*/
function submitXls(formData, params) {
return state => {
const {
applicationName,
hostUrl,
username,
password
} = state.configuration;
const {
case_type,
search_field,
create_new_cases
} = params;
const url = (hostUrl || 'https://www.commcarehq.org').concat('/a/', applicationName, '/importer/excel/bulk_upload_api/');
const workbook = _xlsx.default.utils.book_new();
const worksheet = _xlsx.default.utils.json_to_sheet(formData);
const ws_name = 'SheetJS';
_xlsx.default.utils.book_append_sheet(workbook, worksheet, ws_name); // Generate buffer
const buffer = _xlsx.default.write(workbook, {
type: 'buffer',
bookType: 'xlsx'
}); // xlsx.writeFile(workbook, 'out.xls'); // If needing to write to filesystem
const data = new _formData.default();
data.append('file', buffer, {
filename: 'output.xls'
}); // data.append('file', fs.createReadStream('./out.xls'));
data.append('case_type', case_type);
data.append('search_field', search_field);
data.append('create_new_cases', create_new_cases);
console.log('Posting to url: '.concat(url));
return _languageCommon.http.post({
url,
data,
auth: {
username,
password
},
headers: { ...data.getHeaders()
}
})(state).then(response => {
return { ...state,
data: {
body: response.data
}
};
}).catch(err => {
throw { ...err,
config: {},
request: {}
};
});
};
}
/**
* Submit form data
* @public
* @example
* submit(
* fields(
* field("@", function(state) {
* return {
* "xmlns": "http://openrosa.org/formdesigner/form-id-here"
* };
* }),
* field("question1", dataValue("answer1")),
* field("question2", "Some answer here.")
* )
* )
* @constructor
* @param {Object} formData - Object including form data.
* @returns {Operation}
*/
function submit(formData) {
return state => {
const jsonBody = (0, _languageCommon.expandReferences)(formData)(state);
const body = (0, _js2xmlparser.default)('data', jsonBody);
const {
// this should be called project URL.
// it is what lives after www.commcarehq.org/a/...
applicationName,
username,
password,
appId,
hostUrl
} = state.configuration;
const url = (hostUrl || 'https://www.commcarehq.org').concat('/a/', applicationName, '/receiver/', appId, '/');
console.log('Posting to url: '.concat(url));
console.log('Raw JSON body: '.concat(JSON.stringify(jsonBody)));
console.log('X-form submission: '.concat(body));
return clientPost({
url,
body,
username,
password
}).then(response => {
console.log(`Server repsonded with a ${response.status}:`);
console.log(response);
return { ...state,
references: [response, ...state.references]
};
});
};
}
/**
* Make a GET request to CommCare's Reports API
* and POST the response to somewhere else.
* @public
* @example
* fetchReportData(reportId, params, postUrl)
* @constructor
* @param {String} reportId - API name of the report.
* @param {Object} params - Query params, incl: limit, offset, and custom report filters.
* @param {String} postUrl - Url to which the response object will be posted.
* @returns {Operation}
*/
function fetchReportData(reportId, params, postUrl) {
const {
get,
post
} = _languageHttp.default;
return get(`api/v0.5/configurablereportdata/${reportId}/`, {
query: function (state) {
console.log('getting from url: '.concat(state.configuration.baseUrl, `/api/v0.5/configurablereportdata/${reportId}/`));
console.log('with params: '.concat(params));
return params;
},
callback: function (state) {
var reportData = state.response.body;
return post(postUrl, {
body: reportData
})(state).then(function (state) {
delete state.response;
console.log('fetchReportData succeeded.');
console.log('Posted to: '.concat(postUrl));
return state;
});
}
});
}