81 lines
2.6 KiB
JavaScript
81 lines
2.6 KiB
JavaScript
import { boot } from 'quasar/wrappers';
|
|
import { Connection } from '../js/db/connection';
|
|
import { useUserStore } from '@/stores/user';
|
|
import axios from 'axios';
|
|
import useNotify from '@/composables/useNotify.js';
|
|
import { useAppStore } from '@/stores/app';
|
|
import { Router } from 'src/router';
|
|
const { notify } = useNotify();
|
|
// Be careful when using SSR for cross-request state pollution
|
|
// due to creating a Singleton instance here;
|
|
// If any client changes this (global) instance, it might be a
|
|
// good idea to move this instance creation inside of the
|
|
// "export default () => {}" function below (which runs individually
|
|
// for each client)
|
|
const api = axios.create({
|
|
baseURL: `//${location.hostname}:${location.port}/api/`
|
|
});
|
|
const jApi = new Connection();
|
|
|
|
const onRequestError = error => {
|
|
return Promise.reject(error);
|
|
};
|
|
|
|
const onResponseError = error => {
|
|
const userStore = useUserStore();
|
|
|
|
let message = error.message;
|
|
|
|
const response = error.response;
|
|
const responseData = response && response.data;
|
|
const responseError = responseData && response.data.error;
|
|
if (responseError) {
|
|
message = responseError.message;
|
|
}
|
|
|
|
notify(message, 'negative');
|
|
|
|
if (userStore.isLoggedIn && response?.status === 401) {
|
|
if (!Router) return;
|
|
|
|
Router.push({ name: 'login' });
|
|
userStore.destroy(false);
|
|
} else if (!userStore.isLoggedIn) {
|
|
return Promise.reject(error);
|
|
}
|
|
};
|
|
|
|
export default boot(({ app }) => {
|
|
const userStore = useUserStore();
|
|
const appStore = useAppStore();
|
|
function addToken(config) {
|
|
if (userStore.token) {
|
|
if (!config.headers.Authorization)
|
|
config.headers.Authorization = userStore.token;
|
|
config.headers['Accept-Language'] = appStore.siteLang;
|
|
}
|
|
return config;
|
|
}
|
|
api.interceptors.request.use(addToken, onRequestError);
|
|
api.interceptors.response.use(response => response, onResponseError);
|
|
|
|
jApi.use(addToken);
|
|
jApi.useErrorInterceptor(onResponseError);
|
|
|
|
// for use inside Vue files (Options API) through this.$axios and this.$api
|
|
|
|
app.config.globalProperties.$axios = axios;
|
|
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
|
|
// so you won't necessarily have to import axios in each vue file
|
|
|
|
app.config.globalProperties.$api = api;
|
|
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
|
|
// so you can easily perform requests against your app's API
|
|
|
|
app.config.globalProperties.$jApi = jApi;
|
|
app.provide('jApi', jApi);
|
|
app.provide('api', api);
|
|
});
|
|
|
|
export { api, jApi };
|