37 lines
888 B
TypeScript
37 lines
888 B
TypeScript
import axios, { type AxiosError } from 'axios';
|
|
import { env } from '@/config/env';
|
|
import { STORAGE_KEYS } from '@/utils/storage';
|
|
|
|
const api = axios.create({
|
|
baseURL: env.apiBaseUrl,
|
|
timeout: 10000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
api.interceptors.request.use((config) => {
|
|
const token = localStorage.getItem(STORAGE_KEYS.accessToken);
|
|
|
|
if (token && config.headers) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
|
|
return config;
|
|
});
|
|
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
(error: AxiosError) => {
|
|
if (error.response?.status === 401) {
|
|
localStorage.removeItem(STORAGE_KEYS.authState);
|
|
localStorage.removeItem(STORAGE_KEYS.accessToken);
|
|
localStorage.removeItem(STORAGE_KEYS.user);
|
|
window.location.assign('/login');
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
export default api;
|