Skip to content

Instantly share code, notes, and snippets.

@hrsetyono

hrsetyono/api-helper.js Secret

Created Jan 12, 2021
Embed
What would you like to do?
Helper function for Fetch API
/**
* Simple GET and POST functions that return Promise.
*
* Example:
* myAPI.get( url ).then( result => { ... } );
* myAPI.post( url, data ).then( result => { ... } );
*/
export let myAPI = {
get( endpoint ) {
return window.fetch( endpoint, {
method: 'GET',
headers: { 'Accept': 'application/json' }
} )
.then( this._handleError )
.then( this._handleContentType )
.catch( this._throwError );
},
post( endpoint, body ) {
return window.fetch( endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify( body ),
} )
.then( this._handleError )
.then( this._handleContentType )
.catch( this._throwError );
},
_handleError( err ) {
return err.ok ? err : Promise.reject( err.statusText )
},
_handleContentType( res ) {
const contentType = res.headers.get( 'content-type' );
if( contentType && contentType.includes( 'application/json' ) ) {
return res.json()
}
return Promise.reject( 'Oops, we haven\'t got JSON!' )
},
_throwError( err ) {
throw new Error( err );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment