This commit is contained in:
parent
99151c6692
commit
3676dc46ed
16 changed files with 894 additions and 89 deletions
|
|
@ -1,6 +1,32 @@
|
|||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost/api';
|
||||
|
||||
async function fetchAPI(endpoint, options = {}) {
|
||||
// Track if we're currently refreshing to avoid multiple simultaneous refreshes
|
||||
let isRefreshing = false;
|
||||
let refreshPromise = null;
|
||||
|
||||
// Attempt to refresh the access token
|
||||
async function attemptTokenRefresh() {
|
||||
if (isRefreshing) {
|
||||
// Wait for the existing refresh to complete
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
isRefreshing = true;
|
||||
refreshPromise = fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
}).then(response => {
|
||||
isRefreshing = false;
|
||||
return response.ok;
|
||||
}).catch(() => {
|
||||
isRefreshing = false;
|
||||
return false;
|
||||
});
|
||||
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
async function fetchAPI(endpoint, options = {}, retryAfterRefresh = true) {
|
||||
const response = await fetch(`${API_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers: {
|
||||
|
|
@ -10,6 +36,15 @@ async function fetchAPI(endpoint, options = {}) {
|
|||
credentials: 'include', // Always include credentials
|
||||
});
|
||||
|
||||
// If we get a 401 and haven't already retried, attempt token refresh
|
||||
if (response.status === 401 && retryAfterRefresh) {
|
||||
const refreshed = await attemptTokenRefresh();
|
||||
if (refreshed) {
|
||||
// Retry the original request (but don't retry again if it fails)
|
||||
return fetchAPI(endpoint, options, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API error: ${response.statusText}`);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue