SImplify api calls by using an axios API object

This commit is contained in:
Matthias 2020-05-16 10:52:26 +02:00
parent d614f6879d
commit 8ffc817732
4 changed files with 85 additions and 88 deletions

View File

@ -3,6 +3,9 @@ import './plugins/bootstrap-vue'
import App from './App.vue' import App from './App.vue'
import store from './store' import store from './store'
import router from './router' import router from './router'
import { apiStore } from './shared/apiService'
apiStore.store = store;
Vue.config.productionTip = false Vue.config.productionTip = false

40
src/shared/apiService.js Normal file
View File

@ -0,0 +1,40 @@
import axios from 'axios';
import { apiBase } from '../store/modules/config';
export const apiStore = {store: null}
export const api = axios.create({
baseURL: apiBase,
timeout: 1000,
withCredentials: true,
}
)
api.interceptors.request.use((config) => {
const custconfig = config;
// Merge custconfig dicts
custconfig.headers = {...config.headers, ...apiStore.store.getters['user/apiAuth']};
// Do something before request is sent
// console.log(custconfig)
return custconfig;
}, (error) => Promise.reject(error)
);
api.interceptors.response.use((response) => {
return response;
}
,(err) => {
// console.log(err.response.status);
console.log(err);
if (err.response && err.response.status === 401) {
console.log("Dispatching refresh_token...")
apiStore.store.dispatch('user/refresh_token')
// maybe redirect to /login if needed !
}
return new Promise((resolve, reject) => {
reject(err);
});
// // return Promise.reject(err);
}
);

View File

@ -1,6 +1,4 @@
import axios from 'axios'; import { api } from '../../shared/apiService';
import { apiBase } from './config';
export default { export default {
namespaced: true, namespaced: true,
@ -16,9 +14,6 @@ export default {
balance: {} balance: {}
}, },
getters: { getters: {
apiAuth(state, getters, rootState, rootGetters) {
return rootGetters['user/apiAuth']
},
openTrades(state) { openTrades(state) {
return state.openTrades; return state.openTrades;
// return state.trades.filter((item) => item.is_open); // return state.trades.filter((item) => item.is_open);
@ -55,114 +50,78 @@ export default {
}, },
}, },
actions: { actions: {
getTrades({ commit, getters }) { getTrades({ commit }) {
return axios.get(`${apiBase}/trades`, { console.log("fetching trades")
...getters.apiAuth return api.get('/trades')
})
.then((result) => commit('updateTrades', result.data)) .then((result) => commit('updateTrades', result.data))
.catch(console.error); .catch(console.error);
}, },
getOpentrades({ commit, getters }) { getOpentrades({ commit }) {
return axios.get(`${apiBase}/status`, { return api.get(`/status`)
...getters.apiAuth
})
.then((result) => commit('updateOpenTrades', result.data)) .then((result) => commit('updateOpenTrades', result.data))
.catch(console.error); .catch(console.error);
}, },
getPerformance({ commit, getters }) { getPerformance({ commit }) {
return axios.get(`${apiBase}/performance`, { return api.get(`/performance`)
...getters.apiAuth
})
.then((result) => commit('updatePerformance', result.data)) .then((result) => commit('updatePerformance', result.data))
.catch(console.error); .catch(console.error);
}, },
getWhitelist({ commit, getters }) { getWhitelist({ commit }) {
return axios.get(`${apiBase}/whitelist`, { return api.get(`/whitelist`)
...getters.apiAuth
})
.then((result) => commit('updateWhitelist', result.data)) .then((result) => commit('updateWhitelist', result.data))
.catch(console.error); .catch(console.error);
}, },
getBlacklist({ commit, getters }) { getBlacklist({ commit }) {
return axios.get(`${apiBase}/blacklist`, { return api.get(`/blacklist`)
...getters.apiAuth
})
.then((result) => commit('updateBlacklist', result.data)) .then((result) => commit('updateBlacklist', result.data))
.catch(console.error); .catch(console.error);
}, },
getProfit({ commit, getters }) { getProfit({ commit }) {
return axios.get(`${apiBase}/profit`, { return api.get(`/profit`)
...getters.apiAuth
})
.then((result) => commit('updateProfit', result.data)) .then((result) => commit('updateProfit', result.data))
.catch(console.error); .catch(console.error);
}, },
getBalance({ commit, getters }) { getBalance({ commit }) {
return axios.get(`${apiBase}/balance`, { return api.get(`/balance`)
...getters.apiAuth
})
.then((result) => commit('updateBalance', result.data)) .then((result) => commit('updateBalance', result.data))
.catch(console.error); .catch(console.error);
}, },
getState({ commit, getters, dispatch }) { getState({ commit }) {
return axios.get(`${apiBase}/show_config`, { return api.get(`/show_config`)
...getters.apiAuth
})
.then((result) => commit('updateState', result.data)) .then((result) => commit('updateState', result.data))
.catch((error) => { .catch(console.error);
console.error(error);
if (error.response.status !== 401) {
return new Promise((resolve, reject) => {
reject(error);
});
}
console.log("Dispatching refresh_token...")
dispatch('user/refresh_token', null, { root: true })
return null;
});
}, },
// Post methods // Post methods
// TODO: Migrate calls to API to a seperate module unrelated to vuex? // TODO: Migrate calls to API to a seperate module unrelated to vuex?
startBot({ getters }) { startBot() {
return axios.post(`${apiBase}/start`, {}, { return api.post(`/start`, {})
...getters.apiAuth
})
// .then((result) => )
.catch(console.error); .catch(console.error);
}, },
stopBot({ getters }) { stopBot() {
return axios.post(`${apiBase}/stop`, {}, { return api.post(`/stop`, {})
...getters.apiAuth
})
// .then((result) => )
.catch(console.error); .catch(console.error);
}, },
stopBuy({ getters }) { stopBuy() {
return axios.post(`${apiBase}/stopbuy`, {}, { return api.post(`/stopbuy`, {})
...getters.apiAuth
})
// .then((result) => )
.catch(console.error); .catch(console.error);
}, },
reloadConfig({ getters }) { reloadConfig() {
return axios.post(`${apiBase}/reload_conf`, {}, { return api.post(`/reload_conf`, {})
...getters.apiAuth
})
// .then((result) => )
.catch(console.error); .catch(console.error);
}, },
forcesell({ getters, dispatch }, tradeid) { forcesell({ dispatch }, tradeid) {
console.log(tradeid); console.log(tradeid);
if (tradeid) { if (tradeid) {
const payload = {tradeid}; const payload = { tradeid };
console.log(payload); console.log(payload);
return axios.post(`${apiBase}/forcesell`, payload, { return api.post(`/forcesell`, payload).then(() => {
...getters.apiAuth dispatch('alerts/addAlert', { message: `Sell order for ${tradeid} created` }, { root: true })
}).then(() => {
dispatch('alerts/addAlert', { message: `Sell order for ${tradeid} created`}, { root: true }, )
}).catch((error) => { }).catch((error) => {
console.error(error.response) console.error(error.response)
dispatch('alerts/addAlert', { message: `Failed to create sell order for ${tradeid}`, severity: 'danger'}, { root: true }, ) dispatch('alerts/addAlert', { message: `Failed to create sell order for ${tradeid}`, severity: 'danger' }, { root: true })
}) })
} }
@ -173,13 +132,11 @@ export default {
reject(error); reject(error);
}); });
}, },
forcebuy({getters, dispatch}, payload) { forcebuy({ dispatch }, payload) {
console.log(payload); console.log(payload);
if (payload && payload.pair) { if (payload && payload.pair) {
return axios.post(`${apiBase}/forcebuy`, payload, { return api.post(`/forcebuy`, payload).then(() => {
...getters.apiAuth
}).then(() => {
dispatch('alerts/addAlert', { message: `Buy order for ${payload.pair} created.` }, { root: true }) dispatch('alerts/addAlert', { message: `Buy order for ${payload.pair} created.` }, { root: true })
}).catch((error) => { }).catch((error) => {
console.error(error.response) console.error(error.response)

View File

@ -19,9 +19,7 @@ export default {
let result = {} let result = {}
if (state.accessToken) { if (state.accessToken) {
result = { result = {
headers: {
Authorization: `Bearer ${state.accessToken}`, Authorization: `Bearer ${state.accessToken}`,
}
}; };
} }
else { else {
@ -84,7 +82,6 @@ export default {
}) })
.then((result) => { .then((result) => {
console.log(result.data)
if (result.data.access_token) { if (result.data.access_token) {
commit('setAccessTokens', result.data.access_token); commit('setAccessTokens', result.data.access_token);
} }