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 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
(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); |
aserr13
commented
Jul 1, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment