Last active
September 17, 2022 15:27
-
-
Save mrclay/0eafcbc9ef129d235eea891f251f2bd4 to your computer and use it in GitHub Desktop.
Create a fetch wrapper that allows logging input/output.
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
export interface FetchInfo { | |
uri: RequestInfo; | |
init: RequestInit; | |
res?: unknown; | |
text?: string; | |
error?: unknown; | |
} | |
function defaultLogger({uri, init, text}: FetchInfo): void { | |
console.info({uri, text, init}); | |
} | |
/** | |
* Create a fetch wrapper that allows debugging. | |
* | |
* const fetch = createInspectedFetch(info => console.info(info.text)); | |
*/ | |
export function createInspectedFetch(log = defaultLogger, fetchFunc = fetch) { | |
return (uri: RequestInfo, init: RequestInit) => | |
fetchFunc(uri, init) | |
.then(res => { | |
return res.text().then(text => { | |
log({uri, init, res, text}); | |
return { | |
...res, | |
text: () => Promise.resolve(text), | |
json: () => Promise.resolve(JSON.parse(text)), | |
}; | |
}); | |
}) | |
.catch(error => { | |
log({uri, init, error}); | |
return error; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment