Created
September 8, 2019 23:06
-
-
Save cameck/c682a9f62627a48a886124000a6504e8 to your computer and use it in GitHub Desktop.
An API Call helper function for native fetch calls. Abstracts away a lot of common boilerplate in error handling and JSON parsing. Comments are welcome 🤙
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
/** | |
* Callback for passing back result data. | |
* @callback updateCallback | |
* @param {string} result - A success or error string | |
*/ | |
/** | |
* Callback to run after all is done. | |
* @callback finalCallback | |
*/ | |
/** | |
* A function that handles parsing of fetch requests | |
* @todo add support for better error messaging on non-json responses | |
* @param {object} options - All the fun stuff. | |
* @param {function} options.fetch - The http fetch call | |
* @param {updateCallback} options.successCb - The function to call on success. | |
* @param {updateCallback} options.errorCb - The function to call on error. | |
* @param {finalCallback} options.finallyCb - The function to be called when all is done. | |
* @example | |
* apiCall({ | |
* fetch: () => fetch('https://bananas.com?id=1'), | |
* updateCallback: banana => this.setState({ banana }), | |
* errorCallback: error => this.setState({ error }), | |
* finallyCb: () => this.setState({ loading: false }) | |
* }) | |
*/ | |
export const apiCall = async ({ fetch, successCb, errorCb, finallyCb }) => { | |
try { | |
const resp = await fetch(); | |
const contentType = resp.headers && resp.headers.get('content-type'); | |
if (resp.ok || (contentType && contentType.includes('application/json'))) { | |
const json = await resp.json(); | |
json.error | |
? errorCb(`ERROR: ${json.error.message}. CODE: ${json.error.code}`) | |
: successCb(json); | |
} else { | |
throw new Error(`${resp.statusText}:${resp.status}`); | |
} | |
} catch (error) { | |
errorCb(error.message || error); | |
} finally { | |
finallyCb && finallyCb(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example, is built with the idea of it living in something like React's
componentDidMount
, but should be able to be used most places.