Last active
August 19, 2017 07:25
-
-
Save babie/0c39d95f07595b0183e6335f609304a8 to your computer and use it in GitHub Desktop.
simple rest fetch api
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
| import 'whatwg-fetch' | |
| import store from './store' | |
| function _buildUrl (path, query) { | |
| let url = path | |
| if (query !== undefined) { | |
| let queryArray = [] | |
| for (const key of Object.keys(query)) { | |
| queryArray = [...queryArray, `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`] | |
| } | |
| const queryString = queryArray.join('&') | |
| url = `${url}?${queryString}` | |
| } | |
| return url | |
| } | |
| function _buildOptions (method, data) { | |
| if (method === undefined) { | |
| let error = new Error('method is required') | |
| throw error | |
| } | |
| let options = { | |
| method: method, | |
| headers: { | |
| 'Accept': 'application/json' | |
| } | |
| } | |
| const usersState = store.getState().users | |
| const token = usersState ? usersState.token : undefined | |
| if (token !== undefined) { | |
| options.headers['Authorization'] = `Bearer ${token}` | |
| } | |
| if (data !== undefined) { | |
| if (data instanceof FormData) { | |
| options.body = data | |
| } else { | |
| options.headers['Content-Type'] = 'application/json' | |
| options.body = JSON.stringify(data) | |
| } | |
| } | |
| return options | |
| } | |
| function _parseJson (response) { | |
| if (response.status === 204) { | |
| return | |
| } | |
| return response.json().then((json) => { | |
| if (response.status >= 200 && response.status < 300) { | |
| return json | |
| } else { | |
| let error = new Error(response.statusText) | |
| error.json = json | |
| throw error | |
| } | |
| }) | |
| } | |
| function _request (path, query, data, method) { | |
| const url = _buildUrl(path, query) | |
| const options = _buildOptions(method, data) | |
| return fetch(url, options).then(_parseJson) | |
| } | |
| function get (path, query) { | |
| return _request(path, query, undefined, 'get') | |
| } | |
| function post (path, data, query) { | |
| return _request(path, query, data, 'post') | |
| } | |
| function put (path, data, query) { | |
| return _request(path, query, data, 'put') | |
| } | |
| function patch (path, data, query) { | |
| return _request(path, query, data, 'patch') | |
| } | |
| function del (path, query) { | |
| return _request(path, query, undefined, 'delete') | |
| } | |
| export default { | |
| _buildUrl, | |
| _buildOptions, | |
| _parseJson, | |
| get, | |
| post, | |
| put, | |
| patch, | |
| del | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment