Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Last active May 6, 2022 07:14
Show Gist options
  • Save audunolsen/0eaa8b4bd48bf77ca161140efa0ef7b7 to your computer and use it in GitHub Desktop.
Save audunolsen/0eaa8b4bd48bf77ca161140efa0ef7b7 to your computer and use it in GitHub Desktop.
For when you don't know the response type
/*
Needed in evaluation/Form.js because successful calls to server but
w/ empty data (null from java which fetch retrieves as empty string)
will throw errors because fetch can't parse it as json.
Retrieves either json or text depending on what's available
Didn't change already existing fetchJson to not
risk breaking any exisitng api calls
*/
export default async function fetchData({ url, throw: throwError = true, ...conf }) {
let response = await fetch(url, conf).catch(e => e);
if (response instanceof Error) {
console.error(`Fetching ${url} failed`, response.message);
if (throwError) throw response;
return response;
}
const
text = await response.text(),
json = await Promise.resolve(text).then(JSON.parse).catch(() => ({}));
if (!response.ok) {
console.error(`${url} gave non-ok server response`, `status: ${response.status}`, text);
if (throwError) throw new Error(text);
return new Error(text);
}
return !Object.keys(json).length && text ? text : json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment