updates
This commit is contained in:
@@ -1,35 +1,31 @@
|
||||
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
|
||||
|
||||
// Base URL from environment or default
|
||||
const rawBase = import.meta.env.VITE_API_URL || 'http://localhost:8000';
|
||||
const normalized = String(rawBase).replace(/\/$/, '');
|
||||
const API_BASE_URL = /\/api(\/?$)/i.test(normalized)
|
||||
? normalized
|
||||
: normalized + '/api';
|
||||
|
||||
// Retry configuration
|
||||
const MAX_RETRIES = 3;
|
||||
const RETRY_DELAY = 1000; // 1 second
|
||||
const RETRY_DELAY = 1000;
|
||||
const RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504];
|
||||
|
||||
// Create axios instance with enhanced configuration
|
||||
const apiClient = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 30000, // 30 seconds timeout
|
||||
withCredentials: true, // Enable sending cookies
|
||||
timeout: 30000,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
// Retry logic helper
|
||||
const retryRequest = async (
|
||||
error: AxiosError,
|
||||
retryCount: number = 0
|
||||
): Promise<any> => {
|
||||
const config = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
||||
|
||||
// Don't retry if already retried or not a retryable error
|
||||
|
||||
if (
|
||||
config._retry ||
|
||||
retryCount >= MAX_RETRIES ||
|
||||
@@ -42,7 +38,7 @@ const retryRequest = async (
|
||||
|
||||
config._retry = true;
|
||||
|
||||
// Exponential backoff
|
||||
|
||||
const delay = RETRY_DELAY * Math.pow(2, retryCount);
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
|
||||
@@ -51,10 +47,9 @@ const retryRequest = async (
|
||||
return apiClient.request(config);
|
||||
};
|
||||
|
||||
// Request interceptor - Add token and request ID
|
||||
apiClient.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
// Normalize request URL
|
||||
|
||||
if (config.url && typeof config.url === 'string') {
|
||||
if (config.url.startsWith('/api/')) {
|
||||
config.url = config.url.replace(/^\/api/, '');
|
||||
@@ -62,23 +57,23 @@ apiClient.interceptors.request.use(
|
||||
config.url = config.url.replace(/\/\/+/, '/');
|
||||
}
|
||||
|
||||
// Handle FormData - remove Content-Type header to let browser set it with boundary
|
||||
|
||||
if (config.data instanceof FormData) {
|
||||
delete config.headers['Content-Type'];
|
||||
}
|
||||
|
||||
// Add authorization token
|
||||
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Generate and add request ID for tracking
|
||||
|
||||
const requestId = crypto.randomUUID ? crypto.randomUUID() :
|
||||
`${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
config.headers['X-Request-ID'] = requestId;
|
||||
|
||||
// Add timestamp for request tracking
|
||||
|
||||
(config as any).metadata = { startTime: new Date() };
|
||||
|
||||
return config;
|
||||
@@ -88,19 +83,18 @@ apiClient.interceptors.request.use(
|
||||
}
|
||||
);
|
||||
|
||||
// Response interceptor - Handle errors with retry logic
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
// Log request duration
|
||||
|
||||
const config = response.config as InternalAxiosRequestConfig & { metadata?: any };
|
||||
if (config.metadata?.startTime) {
|
||||
const duration = new Date().getTime() - config.metadata.startTime.getTime();
|
||||
if (duration > 1000) { // Log slow requests (>1s)
|
||||
if (duration > 1000) {
|
||||
console.warn(`Slow request detected: ${config.url} took ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract request ID from response headers for debugging
|
||||
|
||||
const requestId = response.headers['x-request-id'];
|
||||
if (requestId && import.meta.env.DEV) {
|
||||
console.debug(`Request completed: ${config.url} [${requestId}]`);
|
||||
@@ -111,7 +105,7 @@ apiClient.interceptors.response.use(
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
||||
|
||||
// Handle network errors (no response)
|
||||
|
||||
if (!error.response) {
|
||||
if (error.code === 'ECONNABORTED') {
|
||||
return Promise.reject({
|
||||
@@ -120,7 +114,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Retry network errors
|
||||
|
||||
if (originalRequest && !originalRequest._retry) {
|
||||
return retryRequest(error);
|
||||
}
|
||||
@@ -135,12 +129,12 @@ apiClient.interceptors.response.use(
|
||||
const status = error.response.status;
|
||||
const requestId = error.response.headers['x-request-id'];
|
||||
|
||||
// Handle 401 Unauthorized
|
||||
|
||||
if (status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('userInfo');
|
||||
|
||||
// Don't redirect if already on login page
|
||||
|
||||
if (!window.location.pathname.includes('/login')) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
@@ -152,7 +146,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Handle 403 Forbidden
|
||||
|
||||
if (status === 403) {
|
||||
const errorMessage = (error.response?.data as any)?.message || 'You do not have permission to access this resource.';
|
||||
return Promise.reject({
|
||||
@@ -161,7 +155,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Handle 404 Not Found
|
||||
|
||||
if (status === 404) {
|
||||
const errorMessage = (error.response?.data as any)?.message || 'Resource not found.';
|
||||
return Promise.reject({
|
||||
@@ -170,7 +164,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Handle 429 Too Many Requests (rate limiting)
|
||||
|
||||
if (status === 429) {
|
||||
const retryAfter = error.response.headers['retry-after'];
|
||||
return Promise.reject({
|
||||
@@ -180,7 +174,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Handle 5xx server errors with retry
|
||||
|
||||
if (status >= 500 && status < 600) {
|
||||
if (originalRequest && !originalRequest._retry) {
|
||||
return retryRequest(error);
|
||||
@@ -195,7 +189,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// Handle validation errors (400)
|
||||
|
||||
if (status === 400) {
|
||||
const errorData = error.response.data as any;
|
||||
return Promise.reject({
|
||||
@@ -205,7 +199,7 @@ apiClient.interceptors.response.use(
|
||||
});
|
||||
}
|
||||
|
||||
// For other errors, extract message from response
|
||||
|
||||
const errorMessage = (error.response.data as any)?.message || error.message || 'An error occurred';
|
||||
return Promise.reject({
|
||||
...error,
|
||||
|
||||
Reference in New Issue
Block a user