Last active
October 4, 2019 05:57
-
-
Save capJavert/e0ae5b2dc989263d57a5c82450b09c90 to your computer and use it in GitHub Desktop.
Simple fetch retry polyfill.
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
/** | |
* Simple polyfill to support retry of fetch requests | |
*/ | |
;(() => { | |
global.fetchOriginal = global.fetch | |
/** | |
* Create retry fetch with last request arguments | |
* | |
* @param {string} resource request URL or resource to fetch | |
* @param {object} options options for request | |
* @return {Function} new fetch method | |
*/ | |
global.fetchRetry = (resource, options = {}) => | |
/** | |
* Fetch method with preloaded request arguments | |
* @param {[type]} newOptions Override options of last request | |
* @return {Promise} | |
*/ | |
(newOptions = {}) => { | |
const mergedOptions = { | |
...options, | |
...newOptions, | |
// reset signal option from previous fetch | |
signal: newOptions.signal || undefined | |
} | |
return global.fetchOriginal(resource, mergedOptions) | |
} | |
/** | |
* Override fetch and save last request arguments | |
* | |
* @param {string} resource request URL or resource to fetch | |
* @param {object} options options for request | |
* @return {Promise} | |
*/ | |
global.fetch = async (resource, options) => { | |
const response = await global.fetchOriginal(resource, options) | |
response.fetchRetry = global.fetchRetry(resource, options) | |
return response | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment