Fetch and validate JSON (the fetch wrapper that I write over and over again)
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
async function fetchJson(url, options, validate) { | |
const response = await fetch(url, options); | |
let json; | |
let jsonError; | |
try { | |
json = await response.json(); | |
} catch (error) { | |
jsonError = error; | |
} | |
if (json && validate) { | |
validate(json); | |
return json; | |
} | |
if (!response.ok) { | |
throw new Error(`Unexpected Status: ${response.status}`); | |
} | |
if (json) { | |
return json; | |
} | |
throw jsonError; | |
} | |
// Use like this: | |
const json = await fetchJson('https://api.github.com/users/MoritzKn', null, (json) => { | |
if (json.message) { | |
throw new Error(json.message); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment