Skip to content

Instantly share code, notes, and snippets.

@hrsetyono
Created January 12, 2021 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrsetyono/2acecc35d321f1ee21dbf648a1098faa to your computer and use it in GitHub Desktop.
Save hrsetyono/2acecc35d321f1ee21dbf648a1098faa to your computer and use it in GitHub Desktop.
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