Skip to content

Instantly share code, notes, and snippets.

@benjamingr benjamingr/xhr-in-fetch.js
Last active Feb 13, 2019

Embed
What would you like to do?
class Dispatch extends EventTarget {
dispatch(eventName) {
const ev = new Event(eventName);
if (("on" + eventName) in this) {
this["on" + eventName](ev);
}
this.dispatchEvent(ev);
}
}
class XMLHttpRequest extends Dispatch {
open(method, url) {
this.url = url;
this.method = method;
this.headers = new Headers();
this.readyState = 0;
this.responseType = "";
this.upload = new Dispatch();
this._controller = new AbortController();
}
setRequestHeader(key, value) {
x.set(key, value);
}
abort() {
this.upload.dispatch("abort");
this._controller.abort();
}
send(payload) {
this.readyState = 1;
this.dispatch("readystatechanged");
this.upload.dispatch("loadstart");
fetch(this.url, {
method: this.method,
credentials: this.withCredentials,
headers: this.headers,
signal: this._controller.signal,
body: payload
}).then(response => {
this.readyState = 2;
this.responseURL = response.url;
this.responseType = response.type;
this.status = response.status;
this.statusText = response.statusText;
switch (this.responseType) {
case "": return response.text();
case "arraybuffer": return response.arrayBuffer();
case "blob": return response.blob();
case "document": return response.text(); // todo pass through XMLParser
case "json": return response.json();
//todo stream and status 3 and progress
}
}).then(value => {
this.readyState = 4;
this.dispatch("readystatechanged");
this.response = value;
this.upload.dispatch("load");
this.dispatch("load");
this.upload.dispatch("loadend");
this.dispatch("loadend");
}, err => {
this.dispatch("error");
this.upload.dispatch("error")
this.readyState = 4;
this.dispatch("readystatechanged");
});
}
get responseText() {
if(this.response) {
if (this.responseType === "arraybuffer") {
return String.fromCharCode.apply(null, new Uint16Array(this.response)); // slower than StringEncoder/StringDecoder API, but meh
}
if (this.responseType === "json") {
return JSON.stringify(this.response);
}
if(this.response === "blob") {
return ""; //
}
return this.response;
}
}
}
var x = new XMLHttpRequest();
x.open("GET", "./");
x.onload = () => console.log("Onload called");
x.addEventListener("load", console.log);
x.send();
@idoco

This comment has been minimized.

Copy link

commented Feb 13, 2019

small fix in line 21
this.headers.set(key, value);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.