salix-front/src/boot/axios.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-12-20 11:00:36 +00:00
import axios from 'axios';
import { Notify } from 'quasar';
2022-12-20 11:30:25 +00:00
import { useSession } from 'src/composables/useSession';
2023-06-15 09:46:15 +00:00
import { Router } from 'src/router';
import { i18n } from './i18n';
2022-12-20 11:00:36 +00:00
const session = useSession();
const { t } = i18n.global;
2022-12-20 11:00:36 +00:00
axios.defaults.baseURL = '/api/';
2022-12-20 11:00:36 +00:00
const onRequest = (config) => {
const token = session.getToken();
if (token.length && config.headers) {
config.headers.Authorization = token;
}
2022-12-20 11:00:36 +00:00
return config;
};
2022-12-20 11:00:36 +00:00
const onRequestError = (error) => {
return Promise.reject(error);
};
const onResponse = (response) => {
const { method } = response.config;
const isSaveRequest = method === 'patch';
if (isSaveRequest) {
Notify.create({
message: t('globals.dataSaved'),
type: 'positive',
});
}
return response;
};
const onResponseError = (error) => {
let message = '';
const response = error.response;
const responseData = response && response.data;
const responseError = responseData && response.data.error;
if (responseError) {
message = responseError.message;
}
switch (response?.status) {
case 500:
message = 'errors.statusInternalServerError';
break;
case 502:
message = 'errors.statusBadGateway';
break;
case 504:
message = 'errors.statusGatewayTimeout';
break;
}
if (session.isLoggedIn() && response?.status === 401) {
session.destroy();
const hash = window.location.hash;
const url = hash.slice(1);
2023-06-15 09:46:15 +00:00
Router.push({ path: url });
} else if (!session.isLoggedIn()) {
return Promise.reject(error);
}
Notify.create({
message: t(message),
type: 'negative',
});
return Promise.reject(error);
};
axios.interceptors.request.use(onRequest, onRequestError);
axios.interceptors.response.use(onResponse, onResponseError);
2023-03-16 09:54:19 +00:00
export { onRequest, onResponseError };