-
-
Save hrsetyono/2acecc35d321f1ee21dbf648a1098faa to your computer and use it in GitHub Desktop.
Helper function for Fetch API
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
/** | |
* 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