Created
August 18, 2018 20:53
-
-
Save deanohyeah/a88bb85edc1dd4ca5047a3f1b6151d2c to your computer and use it in GitHub Desktop.
Js fetch boilerplate
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
const makeRequest = async function ({ | |
url, | |
body = {}, | |
method = 'GET', | |
headers = {}, | |
}) { | |
const bodyString = JSON.stringify(body) | |
let json | |
const response = await fetch(url, { | |
method, | |
body: bodyString, | |
headers: { | |
'Content-Type': 'application/json', | |
...headers, | |
}, | |
}) | |
if (!response.ok) { | |
let message = `Failed api request to ${url}` | |
try { | |
const responseText = await response.text() | |
if (responseText) { | |
message += responseText | |
} | |
} catch (e) { | |
throw new Error(`Api request to ${url}: ${message} ${response.status}`) | |
} | |
} | |
try { | |
// incase the the server returns invalid json | |
json = await response.json() | |
} catch (e) { | |
return '' | |
} | |
return json | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment