48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
|
|
import axios from 'axios';
|
||
|
|
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
|
||
|
|
|
||
|
|
const API_BASE_URL = '/api';
|
||
|
|
|
||
|
|
class ApiClient {
|
||
|
|
private client: AxiosInstance;
|
||
|
|
|
||
|
|
constructor() {
|
||
|
|
this.client = axios.create({
|
||
|
|
baseURL: API_BASE_URL,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
// Request interceptor to add auth token
|
||
|
|
this.client.interceptors.request.use(
|
||
|
|
(config: InternalAxiosRequestConfig) => {
|
||
|
|
const token = localStorage.getItem('auth_token');
|
||
|
|
if (token && config.headers) {
|
||
|
|
config.headers.Authorization = `Bearer ${token}`;
|
||
|
|
}
|
||
|
|
return config;
|
||
|
|
},
|
||
|
|
(error) => Promise.reject(error)
|
||
|
|
);
|
||
|
|
|
||
|
|
// Response interceptor for error handling
|
||
|
|
this.client.interceptors.response.use(
|
||
|
|
(response: AxiosResponse) => response,
|
||
|
|
(error) => {
|
||
|
|
if (error.response?.status === 401) {
|
||
|
|
localStorage.removeItem('auth_token');
|
||
|
|
window.location.href = '/login';
|
||
|
|
}
|
||
|
|
return Promise.reject(error);
|
||
|
|
}
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
getClient() {
|
||
|
|
return this.client;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const apiClient = new ApiClient().getClient();
|