Created
May 17, 2021 18:51
-
-
Save neodigm/2cfed8cf6e3e24a0fcca19f8f4d692b4 to your computer and use it in GitHub Desktop.
window fetch overload
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
const {fetch: origFetch} = window; | |
window.fetch = async (...args) => { | |
console.log("fetch called with args:", args); | |
const response = await origFetch(...args); | |
/* work with the cloned response in a separate promise | |
chain -- could use the same chain with `await`. */ | |
response | |
.clone() | |
.json() | |
.then(body => console.log("intercepted response:", body)) | |
.catch(err => console.error(err)) | |
; | |
/* the original response can be resolved unmodified: */ | |
//return response; | |
/* or mock the response: */ | |
return { | |
ok: true, | |
status: 200, | |
json: async () => ({ | |
userId: 1, | |
id: 1, | |
title: "Mocked!!", | |
completed: false | |
}) | |
}; | |
}; | |
// test it out with a typical fetch call | |
fetch("https://jsonplaceholder.typicode.com/todos/1") | |
.then(response => response.json()) | |
.then(json => console.log("original caller received:", json)) | |
.catch(err => console.error(err)) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment