76 lines
2.4 KiB
JavaScript
76 lines
2.4 KiB
JavaScript
|
const EEPXHR = (() => {
|
||
|
const send = function(method, url, options, body) {
|
||
|
const xhr = new XMLHttpRequest;
|
||
|
const requestHeaders = new Map;
|
||
|
|
||
|
if('headers' in options && typeof options.headers === 'object')
|
||
|
for(const name in options.headers)
|
||
|
if(options.headers.hasOwnProperty(name))
|
||
|
requestHeaders.set(name.toLowerCase(), options.headers[name]);
|
||
|
|
||
|
if(typeof options.upload === 'function') {
|
||
|
xhr.upload.onloadstart = ev => options.upload(ev);
|
||
|
xhr.upload.onprogress = ev => options.upload(ev);
|
||
|
xhr.upload.onloadend = ev => options.upload(ev);
|
||
|
}
|
||
|
|
||
|
if(options.authed)
|
||
|
xhr.withCredentials = true;
|
||
|
|
||
|
if(typeof options.timeout === 'number')
|
||
|
xhr.timeout = options.timeout;
|
||
|
|
||
|
if(typeof options.type === 'string')
|
||
|
xhr.responseType = options.type;
|
||
|
|
||
|
if(typeof options.abort === 'function')
|
||
|
options.abort(() => xhr.abort());
|
||
|
|
||
|
return new Promise((resolve, reject) => {
|
||
|
let responseHeaders = undefined;
|
||
|
|
||
|
xhr.onload = ev => resolve({
|
||
|
status: xhr.status,
|
||
|
body: () => xhr.response,
|
||
|
headers: () => {
|
||
|
if(responseHeaders !== undefined)
|
||
|
return responseHeaders;
|
||
|
|
||
|
responseHeaders = new Map;
|
||
|
|
||
|
const raw = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/);
|
||
|
for(const name in raw)
|
||
|
if(raw.hasOwnProperty(name)) {
|
||
|
const parts = raw[name].split(': ');
|
||
|
responseHeaders.set(parts.shift(), parts.join(': '));
|
||
|
}
|
||
|
|
||
|
return responseHeaders;
|
||
|
},
|
||
|
});
|
||
|
|
||
|
xhr.onabort = ev => reject({
|
||
|
abort: true,
|
||
|
xhr: xhr,
|
||
|
ev: ev,
|
||
|
});
|
||
|
|
||
|
xhr.onerror = ev => reject({
|
||
|
abort: false,
|
||
|
xhr: xhr,
|
||
|
ev: ev,
|
||
|
});
|
||
|
|
||
|
xhr.open(method, url);
|
||
|
for(const [name, value] of requestHeaders)
|
||
|
xhr.setRequestHeader(name, value);
|
||
|
xhr.send(body);
|
||
|
});
|
||
|
};
|
||
|
|
||
|
return {
|
||
|
post: (url, options, body) => send('POST', url, options, body),
|
||
|
delete: (url, options, body) => send('DELETE', url, options, body),
|
||
|
};
|
||
|
})();
|