Skip to content

Instantly share code, notes, and snippets.

@mrclay
Last active September 17, 2022 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrclay/0eafcbc9ef129d235eea891f251f2bd4 to your computer and use it in GitHub Desktop.
Save mrclay/0eafcbc9ef129d235eea891f251f2bd4 to your computer and use it in GitHub Desktop.
Create a fetch wrapper that allows logging input/output.
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