Skip to content

Instantly share code, notes, and snippets.

@KhalilZaidoun
Last active March 29, 2018 10:39
Show Gist options
  • Save KhalilZaidoun/4c6a724cd37ba6cdec800109ed019b4b to your computer and use it in GitHub Desktop.
Save KhalilZaidoun/4c6a724cd37ba6cdec800109ed019b4b to your computer and use it in GitHub Desktop.
javascript native request utility
// For more documentations refer to https://github.github.io/fetch/
import 'whatwg-fetch';
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
export function parseJSON(response) {
return response.text().then(text => (text ? JSON.parse(text) : {}));
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} An object containing either "data" or "err"
*/
export default function(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
// .then((data) => ({data}))
// .catch((err) => ({err}));
}
/*
import request from '.../request
request(URL, {headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(resp=> {
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment