Created
October 21, 2016 14:00
-
-
Save bnhansn/b2358e5ec5c3087a4f5fb9bbf0f8a385 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const API = process.env.REACT_APP_API_URL; | |
| function headers() { | |
| const token = JSON.parse(localStorage.getItem('token')); | |
| return { | |
| Accept: 'application/json', | |
| 'Content-Type': 'application/json', | |
| Authorization: `Bearer: ${token}`, | |
| }; | |
| } | |
| function parseResponse(response) { | |
| return response.json().then((json) => { | |
| if (!response.ok) { | |
| return Promise.reject(json); | |
| } | |
| return json; | |
| }); | |
| } | |
| function queryString(params) { | |
| const query = Object.keys(params) | |
| .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`) | |
| .join('&'); | |
| return `${query.length ? '?' : ''}${query}`; | |
| } | |
| export default { | |
| fetch(url, params = {}) { | |
| return fetch(`${API}${url}${queryString(params)}`, { | |
| method: 'GET', | |
| headers: headers(), | |
| }) | |
| .then(parseResponse); | |
| }, | |
| post(url, data) { | |
| const body = JSON.stringify(data); | |
| return fetch(`${API}${url}`, { | |
| method: 'POST', | |
| headers: headers(), | |
| body, | |
| }) | |
| .then(parseResponse); | |
| }, | |
| patch(url, data) { | |
| const body = JSON.stringify(data); | |
| return fetch(`${API}${url}`, { | |
| method: 'PATCH', | |
| headers: headers(), | |
| body, | |
| }) | |
| .then(parseResponse); | |
| }, | |
| delete(url) { | |
| return fetch(`${API}${url}`, { | |
| method: 'DELETE', | |
| headers: headers(), | |
| }) | |
| .then(parseResponse); | |
| }, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment