2020-11-06 00:15:40 +00:00
|
|
|
import axios, { AxiosInstance, AxiosError } from 'axios';
|
2020-10-02 07:13:14 +00:00
|
|
|
import { boot } from 'quasar/wrappers';
|
2020-10-16 07:38:14 +00:00
|
|
|
import config from '../config';
|
2020-10-18 23:45:06 +00:00
|
|
|
import { Store } from 'vuex';
|
2020-10-29 00:39:06 +00:00
|
|
|
import { StateInterface } from 'src/store';
|
2020-10-02 07:13:14 +00:00
|
|
|
|
|
|
|
declare module 'vue/types/vue' {
|
|
|
|
interface Vue {
|
|
|
|
$axios: AxiosInstance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-15 17:51:30 +00:00
|
|
|
export default boot<Store<StateInterface>>(({ Vue, store, router }) => {
|
2020-10-02 07:13:14 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|
|
|
Vue.prototype.$axios = axios;
|
2020-10-15 01:35:44 +00:00
|
|
|
axios.defaults.baseURL = config.baseURL;
|
|
|
|
|
2020-11-06 00:15:40 +00:00
|
|
|
/***
|
|
|
|
* Intercept requests and insert Token if available
|
|
|
|
*/
|
2020-10-16 07:38:14 +00:00
|
|
|
axios.interceptors.request.use(config => {
|
2020-11-04 22:53:10 +00:00
|
|
|
const session = store.state.session.currentSession;
|
|
|
|
if (session?.token) {
|
|
|
|
config.headers = { Authorization: 'Bearer ' + session.token };
|
2020-10-16 07:38:14 +00:00
|
|
|
}
|
|
|
|
return config;
|
|
|
|
});
|
2020-11-06 00:15:40 +00:00
|
|
|
|
|
|
|
/***
|
2020-11-06 09:52:51 +00:00
|
|
|
* Intercept responses
|
|
|
|
* - filter 401 --> logout
|
2020-11-15 17:51:30 +00:00
|
|
|
* - filter timeout or 502-504 --> backendOffline
|
2020-11-06 00:15:40 +00:00
|
|
|
*/
|
|
|
|
axios.interceptors.response.use(
|
|
|
|
response => response,
|
|
|
|
error => {
|
2020-11-06 09:52:51 +00:00
|
|
|
if (error) {
|
2020-11-06 00:15:40 +00:00
|
|
|
const e = <AxiosError>error;
|
2020-11-09 02:40:51 +00:00
|
|
|
if (
|
|
|
|
e.code === 'ECONNABORTED' ||
|
2020-11-15 17:51:30 +00:00
|
|
|
(e.response && e.response.status >= 502 && e.response.status <= 504)
|
2020-11-09 02:40:51 +00:00
|
|
|
) {
|
2020-11-15 17:51:30 +00:00
|
|
|
return router.push({
|
|
|
|
name: 'offline',
|
|
|
|
query: { redirect: router.currentRoute.fullPath }
|
2020-11-14 14:04:42 +00:00
|
|
|
});
|
2020-11-15 17:51:30 +00:00
|
|
|
} else if (e.response && e.response.status == 401) {
|
2021-01-21 20:07:49 +00:00
|
|
|
if (router.currentRoute.name !== 'login') return store.dispatch('session/clearCurrent');
|
2020-11-06 00:15:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
|
|
}
|
|
|
|
);
|
2020-10-02 07:13:14 +00:00
|
|
|
});
|
2020-10-15 09:23:41 +00:00
|
|
|
|
|
|
|
export { axios };
|