Last active
September 18, 2017 16:21
-
-
Save victorwpbastos/335f8d075da1a6776738ef1888699f6a to your computer and use it in GitHub Desktop.
Fetch interceptor
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
let _fetch = window.fetch; | |
window.fetch = (url, options) => { | |
return new Promise((resolve, reject) => { | |
let p = _fetch(url, options); | |
document.dispatchEvent(new CustomEvent('fetchStart', { detail: p })); | |
p.then(response => { | |
if (response.ok) { | |
return response; | |
} else { | |
let error = new Error(response.statusText); | |
error.response = response; | |
throw error; | |
} | |
}).catch(error => { | |
document.dispatchEvent(new CustomEvent('fetchError', { detail: error.response })); | |
reject(error); | |
}).then(response => { | |
document.dispatchEvent(new CustomEvent('fetchEnd', { detail: response })); | |
resolve(response); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment