mirror of
https://github.com/Sea-Haven-Industries/proposal-system.git
synced 2026-10-07 02:22:02 +00:00
63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
|
|
import axios from 'axios';
|
||
|
|
import { API_URL, STORAGE_KEY_TOKEN } from '../../constants';
|
||
|
|
|
||
|
|
const apiClient = axios.create({
|
||
|
|
baseURL: API_URL,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
Accept: 'application/json',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
apiClient.interceptors.request.use(
|
||
|
|
(config) => {
|
||
|
|
const tokenData = window.localStorage.getItem(STORAGE_KEY_TOKEN);
|
||
|
|
if (tokenData) {
|
||
|
|
try {
|
||
|
|
const parsed = JSON.parse(tokenData);
|
||
|
|
if (parsed?.token) {
|
||
|
|
config.headers.Authorization = `Bearer ${parsed.token}`;
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
// Invalid token data
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return config;
|
||
|
|
},
|
||
|
|
(error) => Promise.reject(error)
|
||
|
|
);
|
||
|
|
|
||
|
|
apiClient.interceptors.response.use(
|
||
|
|
(response) => response,
|
||
|
|
(error) => {
|
||
|
|
if (error.response) {
|
||
|
|
const { status, data } = error.response;
|
||
|
|
|
||
|
|
if (status === 401) {
|
||
|
|
window.localStorage.removeItem(STORAGE_KEY_TOKEN);
|
||
|
|
window.location.href = '/login';
|
||
|
|
return Promise.reject(new Error('Session expired. Please log in again.'));
|
||
|
|
}
|
||
|
|
|
||
|
|
if (status === 403) {
|
||
|
|
return Promise.reject(new Error('You do not have permission to perform this action.'));
|
||
|
|
}
|
||
|
|
|
||
|
|
if (status === 404) {
|
||
|
|
return Promise.reject(new Error('The requested resource was not found.'));
|
||
|
|
}
|
||
|
|
|
||
|
|
const message = data?.detail || data?.title || data?.message || 'An error occurred';
|
||
|
|
return Promise.reject(new Error(message));
|
||
|
|
}
|
||
|
|
|
||
|
|
if (error.request) {
|
||
|
|
return Promise.reject(new Error('No response from server. Please check your connection.'));
|
||
|
|
}
|
||
|
|
|
||
|
|
return Promise.reject(error);
|
||
|
|
}
|
||
|
|
);
|
||
|
|
|
||
|
|
export default apiClient;
|