Last active
December 4, 2017 21:28
-
-
Save iinsta/86b6b1abbb2e7473229fd7b01092343d to your computer and use it in GitHub Desktop.
No fetch :) just XHR, because we can abort the request now!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* usage | |
* | |
* componentDidMount() { | |
* likefetch('www.example.com/api/', {method: 'post', body: JSON.stringify({data: 123})}, c => this.xhr = c) | |
* } | |
* componentWillUnmount() { | |
* this.xhr && this.xhr.abort() | |
* } | |
* | |
*/ | |
function likefetch(url, options, cb) { | |
options = options || {}; | |
return new Promise( (resolve, reject) => { | |
let request = new XMLHttpRequest(); | |
request.open(options.method || 'get', url); | |
for (let i in options.headers) { | |
request.setRequestHeader(i, options.headers[i]); | |
} | |
request.withCredentials = options.credentials=='include'; | |
request.onload = () => { | |
resolve(response()); | |
}; | |
request.onerror = reject; | |
request.send(options.body); | |
typeof cb === 'function' && cb(request); | |
function response() { | |
let keys = [], | |
all = [], | |
headers = {}, | |
header; | |
request.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, (m, key, value) => { | |
keys.push(key = key.toLowerCase()); | |
all.push([key, value]); | |
header = headers[key]; | |
headers[key] = header ? `${header},${value}` : value; | |
}); | |
return { | |
ok: (request.status/100|0) == 2, // 200-299 | |
status: request.status, | |
statusText: request.statusText, | |
url: request.responseURL, | |
clone: response, | |
text: () => Promise.resolve(request.responseText), | |
json: () => Promise.resolve(request.responseText).then(JSON.parse), | |
blob: () => Promise.resolve(new Blob([request.response])), | |
headers: { | |
keys: () => keys, | |
entries: () => all, | |
get: n => headers[n.toLowerCase()], | |
has: n => n.toLowerCase() in headers | |
} | |
}; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment