-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
63 lines (52 loc) · 1.61 KB
/
client.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
'use strict';
/* Arguments: {
url: "url",
method: "http method",
mode: "cors",
body: "data[args.body]"
key: "data[key] = result"
}*/
exports.fetch = (args, data, callback) => {
if (typeof args.url !== 'string' && typeof data.url !== 'string') {
return callback(new Error('Flow-http.request: Invalid url.'));
}
const method = (data.method || args.method || 'GET').toUpperCase();
const options = {
method: method,
credentials: 'same-origin',
mode: args.mode || 'cors'
};
// Request body
if (typeof args.body === 'string' && data[args.body] !== undefined) {
options.body = data[args.body];
}
let error;
fetch(args.url || data.url, options).then((response) => {
if (!response.ok) {
error = true;
}
switch (response.headers.get('content-type')) {
case "application/json":
return response.json();
case "text/plain":
case "text/html":
case "text/css":
return response.text();
default:
return response.blob();
}
// TODO https://developer.mozilla.org/en-US/docs/Web/API/Body
// check if body implements a streaming interfaces
}).then((res) => {
if (error) {
if (typeof res === 'string') {
callback(new Error(res));
} else {
callback(res);
}
} else {
args.key ? (data[args.key] = res) : (data = res);
callback(null, data);
}
}).catch(callback);
};