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
251 lines (231 loc) · 6.2 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
/** @module Adaptor */
import {
execute as commonExecute,
http,
expandReferences,
} from '@openfn/language-common';
import request from 'superagent';
import FormData from 'form-data';
import js2xmlparser from 'js2xmlparser';
import Adaptor from 'language-http';
import xlsx from 'xlsx';
/**
* 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}
*/
export 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 commonExecute(...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) => {
request
.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}
*/
export function submitXls(formData, params) {
return state => {
const {
applicationName,
hostUrl,
username,
password,
} = state.configuration;
const json = expandReferences(formData)(state);
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.utils.book_new();
const worksheet = xlsx.utils.json_to_sheet(json);
const ws_name = 'SheetJS';
xlsx.utils.book_append_sheet(workbook, worksheet, ws_name);
// Generate buffer
const buffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });
// xlsx.writeFile(workbook, 'out.xls'); // If needing to write to filesystem
const data = new FormData();
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 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}
*/
export function submit(formData) {
return state => {
const jsonBody = expandReferences(formData)(state);
const body = js2xmlparser('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}
*/
export function fetchReportData(reportId, params, postUrl) {
const { get, post } = Adaptor;
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;
});
},
});
}
export {
fn,
alterState,
arrayToString,
combine,
dataPath,
dataValue,
each,
field,
fields,
http,
lastReferenceValue,
merge,
sourceValue,
} from '@openfn/language-common';