Created
January 11, 2016 18:27
-
-
Save richardscarrott/3e1b3090cfcae6965efb to your computer and use it in GitHub Desktop.
Wrapper around `window.fetch`
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
'use strict'; | |
// http://stackoverflow.com/questions/31089801/extending-error-in-javascript-with-es6-syntax | |
class ExtendableError extends Error { | |
constructor(message) { | |
super(); | |
this.message = message; | |
this.stack = (new Error()).stack; | |
this.name = this.constructor.name; | |
} | |
} | |
class NetworkError extends ExtendableError { | |
constructor(message, status, json = {}) { | |
super(message); | |
this.status = status; | |
this.response = json; | |
} | |
} | |
export default NetworkError; |
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
import NetworkError from '../utils/NetworkError'; | |
function checkStatus(response) { | |
if (response.ok) { | |
return response; | |
} | |
throw response; | |
}; | |
function parseJson(response) { | |
if (response.status === 201 || response.status === 204) { | |
return {}; | |
} | |
return response.json(); | |
}; | |
function parseError(response) { | |
// Handle HTTP error statuses | |
if (response && typeof response.json === 'function') { | |
return parseJson(response) | |
.then(json => { | |
throw new NetworkError(response.statusText, response.status, json); | |
}, () => { | |
throw new NetworkError(response.statusText, response.status); | |
}); | |
} | |
// Handle Network errors, e.g. cors etc. | |
throw new NetworkError(response.message); | |
} | |
function xhr(url, params = {}) { | |
params = Object.assign({ | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
} | |
}, params); | |
return fetch(url, params) | |
.then(checkStatus) | |
.then(parseJson, parseError); | |
}; | |
export default xhr; | |
// Usage: | |
// xhr('/Users').then((data) => { console.log('success', data); }, (error) => { console.log('error', error); }).catch((error) => { console.log('runtime error', error); }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment