-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelementary-http.js
More file actions
62 lines (54 loc) · 1.48 KB
/
Copy pathelementary-http.js
File metadata and controls
62 lines (54 loc) · 1.48 KB
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
export default (name, settings, app) => {
const { encode, decode, update, tc} = app;
const state = {};
function error(msg, data){
console.error(`[${name}] ${msg}`, data);
}
function debug(msg, data) {
if (settings.debug) console.log(`[http][${name}] ${msg}`, data);
}
function decodeJson(raw) {
try {
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function getHeadersAsObject(xhr){
let headers = {}
xhr.getAllResponseHeaders()
.split('\u000d\u000a')
.forEach((line) => {
if (line.length > 0)
{
let delimiter = '\u003a\u0020',
header = line.split(delimiter)
headers[header.shift().toLowerCase()] = header.join(delimiter)
}
})
return headers
}
function jsonOrRaw(headers, req) {
return headers['content-type'] === 'application/json' ?
(decodeJson(req.responseText) || req.responseText) : req.responseText;
}
return (encoders, enc, model) => {
var {err, value} = encode(enc, model);
if (err) {
error("error encoding request", err);
} else {
const req = new XMLHttpRequest();
req.open((value.method||'get').toUpperCase(), value.url||'/' );
req.send();
req.onload = function () {
const headers = getHeadersAsObject(req);
update({
effect: name,
status: req.status,
headers: headers,
body: jsonOrRaw(headers, req)
})
}
}
};
}