mirror of
https://github.com/Sea-Haven-Industries/proposal-system.git
synced 2026-09-30 13:33:15 +00:00
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
|
|
import axios from 'axios';
|
||
|
|
import Config from '../../config';
|
||
|
|
import { tokenStorage } from '../storage';
|
||
|
|
|
||
|
|
const apiClient = axios.create({
|
||
|
|
baseURL: Config.API_URL,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
Accept: 'application/json',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
apiClient.interceptors.request.use(
|
||
|
|
async (config) => {
|
||
|
|
const tokens = await tokenStorage.get();
|
||
|
|
if (tokens?.accessToken) {
|
||
|
|
config.headers.Authorization = `Bearer ${tokens.accessToken}`;
|
||
|
|
}
|
||
|
|
return config;
|
||
|
|
},
|
||
|
|
(error) => Promise.reject(error),
|
||
|
|
);
|
||
|
|
|
||
|
|
apiClient.interceptors.response.use(
|
||
|
|
(response) => response,
|
||
|
|
(error) => {
|
||
|
|
if (error.response) {
|
||
|
|
const { status, data } = error.response;
|
||
|
|
|
||
|
|
if (status === 401) {
|
||
|
|
tokenStorage.clear();
|
||
|
|
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;
|