new awesome build
This commit is contained in:
73
APP_UI/src/composables/useApi.js
Normal file
73
APP_UI/src/composables/useApi.js
Normal file
@@ -0,0 +1,73 @@
|
||||
import axios from 'axios';
|
||||
import { useAppConfig } from './useAppConfig';
|
||||
|
||||
// Singleton instances
|
||||
const apiClient = axios.create();
|
||||
const profilesApiClient = axios.create();
|
||||
|
||||
// Helper to get base URLs
|
||||
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
||||
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
||||
|
||||
// Add interceptors to handle Auth and Dynamic Base URLs
|
||||
const setupInterceptors = (instance, getBase) => {
|
||||
instance.interceptors.request.use((reqConfig) => {
|
||||
const { config } = useAppConfig();
|
||||
reqConfig.baseURL = getBase(config.value);
|
||||
|
||||
const token = localStorage.getItem('ovpmon_token');
|
||||
if (token) {
|
||||
reqConfig.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return reqConfig;
|
||||
});
|
||||
|
||||
instance.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
// Redirecting using window.location for absolute refresh
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
setupInterceptors(apiClient, getBaseUrl);
|
||||
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
||||
|
||||
export function useApi() {
|
||||
const fetchStats = async () => {
|
||||
const res = await apiClient.get('/stats');
|
||||
return res.data;
|
||||
};
|
||||
|
||||
const fetchClientHistory = async (clientId, range) => {
|
||||
const res = await apiClient.get(`/stats/${clientId}`, { params: { range } });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
const fetchAnalytics = async (range) => {
|
||||
const res = await apiClient.get('/analytics', { params: { range } });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
const fetchCertificates = async () => {
|
||||
const res = await apiClient.get('/certificates');
|
||||
return res.data;
|
||||
};
|
||||
|
||||
return {
|
||||
apiClient,
|
||||
profilesApiClient,
|
||||
fetchStats,
|
||||
fetchClientHistory,
|
||||
fetchAnalytics,
|
||||
fetchCertificates
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user