generalize request function

This commit is contained in:
Jonathan Rainville 2018-09-06 16:11:56 -04:00 committed by Pascal Precht
parent 3495f9fbb8
commit 89cbbeec27
No known key found for this signature in database
GPG Key ID: 0EE28D8D6FD85D7D
1 changed files with 10 additions and 31 deletions

View File

@ -2,10 +2,10 @@ import axios from "axios";
import constants from '../constants'; import constants from '../constants';
import {get as cacheGet} from '../services/cache'; import {get as cacheGet} from '../services/cache';
function get(path, params = {}, endpoint) { function request(type, path, params = {}, endpoint) {
axios.defaults.headers.common['Authorization'] = cacheGet('token'); axios.defaults.headers.common['Authorization'] = cacheGet('token');
const callback = params.callback || function(){}; const callback = params.callback || function(){};
return axios.get((endpoint || constants.httpEndpoint) + path, params) return axios[type]((endpoint || constants.httpEndpoint) + path, params)
.then((response) => { .then((response) => {
const data = (response.data && response.data.error) ? {error: response.data.error} : {response, error: null}; const data = (response.data && response.data.error) ? {error: response.data.error} : {response, error: null};
callback(data.error, data.response); callback(data.error, data.response);
@ -17,37 +17,16 @@ function get(path, params = {}, endpoint) {
}); });
} }
function post(path, params = {}) { function get() {
axios.defaults.headers.common['Authorization'] = cacheGet('token'); return request('get', ...arguments);
const callback = params.callback || function(){};
delete params.callback;
return axios.post(constants.httpEndpoint + path, params)
.then((response) => {
const data = (response.data && response.data.error) ? {error: response.data.error} : {response, error: null};
callback(data.error, data.response);
return data;
})
.catch((error) => {
const data = {response: null, error: error.message || 'Something bad happened'};
callback(data.error, data.response);
return data;
});
} }
function destroy(path, params = {}) { function post() {
axios.defaults.headers.common['Authorization'] = cacheGet('token'); return request('post', ...arguments);
const callback = params.callback || function(){}; }
return axios.delete(constants.httpEndpoint + path, params)
.then((response) => { function destroy() {
const data = (response.data && response.data.error) ? {error: response.data.error} : {response, error: null}; return request('delete', ...arguments);
callback(data.error, data.response);
return data;
})
.catch((error) => {
const data = {response: null, error: error.message || 'Something bad happened'};
callback(data.error, data.response);
return data;
});
} }
export function postCommand(payload) { export function postCommand(payload) {