Last active
March 24, 2023 15:44
-
-
Save dgraham/92e4c45da3707a3fe789 to your computer and use it in GitHub Desktop.
Simple window.fetch wrapper.
This file contains 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
(function() { | |
function status(response) { | |
if (response.ok) { | |
return response | |
} else { | |
var error = new Error(response.statusText || response.status) | |
error.response = response | |
throw error | |
} | |
} | |
function headers(options) { | |
options = options || {} | |
options.headers = options.headers || {} | |
options.headers['X-Requested-With'] = 'XMLHttpRequest' | |
return options | |
} | |
function credentials(options) { | |
if (options == null) { | |
options = {} | |
} | |
if (options.credentials == null) { | |
options.credentials = 'same-origin' | |
} | |
return options | |
} | |
function json(response) { | |
return response.json() | |
} | |
function text(response) { | |
return response.text() | |
} | |
$.fetch = function(url, options) { | |
options = headers(credentials(options)) | |
return fetch(url, options).then(status) | |
} | |
$.fetchText = function(url, options) { | |
options = headers(credentials(options)) | |
return fetch(url, options).then(status).then(text) | |
} | |
$.fetchJSON = function(url, options) { | |
options = headers(credentials(options)) | |
options.headers['Accept'] = 'application/json' | |
return fetch(url, options).then(status).then(json) | |
} | |
$.fetchPoll = function(url, options) { | |
return new Promise(function(resolve, reject) { | |
function poll(wait) { | |
function done(response) { | |
switch (response.status) { | |
case 200: | |
resolve(response) | |
break | |
case 202: | |
setTimeout(poll, wait, wait * 1.5) | |
break | |
default: | |
var error = new Error(response.statusText || response.status) | |
error.response = response | |
reject(error) | |
break | |
} | |
} | |
$.fetch(url, options).then(done, reject) | |
} | |
poll(1000) | |
}) | |
} | |
}).call(this); |
Just to point out, jQuery doesn't throw on 304 and some other 300 codes.
see https://github.com/glazedio/frisbee if you need something more advanced
In the same vein as this gist, this lib is a tiny wrapper around fetch with a pleasant syntax.
This is awesome.
When I get an error response (like a 401 unauthorized) how do you handle that?
EDIT: I guess what I mean is, how do I get the error message from the server?
Try to download the system bin and complete it with a new launch code
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome.
When I get an error response (like a 401 unauthorized) how do you handle that?
EDIT: I guess what I mean is, how do I get the error message from the server?