-
Notifications
You must be signed in to change notification settings - Fork 194
/
utils.js
83 lines (68 loc) · 1.75 KB
/
utils.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
var Promise = require('es6-promise').Promise;
function request(url, opts) {
// Return a new promise.
return new Promise(function(resolve, reject) {
opts = defaults(opts, {
method: "GET",
headers: {}
});
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open(opts.method, url);
for (var header in opts.headers) {
req.setRequestHeader(header, opts.headers[header]);
}
req. {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req. {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
function defaults(opts, defaultOpts) {
var r = Object.create(defaultOpts);
if (!opts) { return r; }
for (var key in opts) if (opts.hasOwnProperty(key)) {
r[key] = opts[key];
}
return r;
}
function toQuerystring(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
var strToEls = (function () {
var tmpEl = document.createElement('div');
return function (str) {
var r = document.createDocumentFragment();
tmpEl.innerHTML = str;
while (tmpEl.childNodes[0]) {
r.appendChild(tmpEl.childNodes[0]);
}
return r;
};
}());
module.exports = {
request: request,
defaults: defaults,
toQuerystring: toQuerystring,
strToEls: strToEls
};