refactor: streamline token refresh logic by retrying queued requests with new tokens and update public API endpoint list.
This commit is contained in:
@@ -27,10 +27,17 @@ let failedQueue: Array<{
|
||||
config: InternalAxiosRequestConfig;
|
||||
}> = [];
|
||||
|
||||
const processQueue = (error: AxiosError | null) => {
|
||||
const processQueue = (error: AxiosError | null, newToken?: string) => {
|
||||
failedQueue.forEach((prom) => {
|
||||
if (error) {
|
||||
prom.reject(error);
|
||||
} else {
|
||||
// Update the queued request with new token and retry
|
||||
if (newToken && prom.config.headers) {
|
||||
prom.config.headers.Authorization = `Bearer ${newToken}`;
|
||||
}
|
||||
// Resolve to trigger the .then() which will retry the request
|
||||
api(prom.config).then(prom.resolve).catch(prom.reject);
|
||||
}
|
||||
});
|
||||
failedQueue = [];
|
||||
@@ -62,11 +69,15 @@ api.interceptors.request.use(
|
||||
}
|
||||
);
|
||||
|
||||
// Public API endpoints that don't require authentication
|
||||
// Public API endpoints that don't require authentication (everything else requires auth)
|
||||
const publicEndpoints = [
|
||||
'/agents',
|
||||
'/auth/login',
|
||||
'/auth/register',
|
||||
'/auth/refresh',
|
||||
'/auth/forgot-password',
|
||||
'/auth/reset-password',
|
||||
'/auth/verify-email',
|
||||
'/agent-types',
|
||||
'/profiles',
|
||||
];
|
||||
|
||||
// Check if URL is a public endpoint
|
||||
@@ -110,16 +121,9 @@ api.interceptors.response.use(
|
||||
}
|
||||
|
||||
if (isRefreshing) {
|
||||
// If already refreshing, queue this request
|
||||
return new Promise((resolve, reject) => {
|
||||
// If already refreshing, queue this request to be retried after refresh completes
|
||||
return new Promise<AxiosResponse>((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject, config: originalRequest });
|
||||
}).then(() => {
|
||||
// Retry with new token
|
||||
const newToken = localStorage.getItem('accessToken');
|
||||
if (newToken && originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`;
|
||||
}
|
||||
return api(originalRequest);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -160,8 +164,8 @@ api.interceptors.response.use(
|
||||
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
|
||||
}
|
||||
|
||||
// Process queued requests
|
||||
processQueue(null);
|
||||
// Process queued requests with new token
|
||||
processQueue(null, newAccessToken);
|
||||
isRefreshing = false;
|
||||
|
||||
// Retry original request
|
||||
|
||||
Reference in New Issue
Block a user