Skip to content

Instantly share code, notes, and snippets.

@Josema
Created July 7, 2021 20:15
Show Gist options
  • Save Josema/a3d94a519eeee50e52d31498f85c2e34 to your computer and use it in GitHub Desktop.
Save Josema/a3d94a519eeee50e52d31498f85c2e34 to your computer and use it in GitHub Desktop.
async function fetchWrapper({ url, method, headers = {}, body }) {
const opts = { method, headers }
if (method === 'POST' && typeof body === 'string') {
headers['Content-Type'] = 'application/x-www-form-urlencoded'
opts.body = body
}
const response = await fetch(url, opts)
let output
try {
output = await response.clone().json()
} catch (e) {
output = await response.text()
}
if (typeof output == 'string') {
return output
}
if (output.hasOwnProperty('error')) {
throw output
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment