fix: window scoped state for token refresh

This commit is contained in:
2025-05-30 21:25:39 +02:00
parent 8a28fca3d9
commit 03697b2f67
4 changed files with 20 additions and 5 deletions

6
web/globals.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
interface Window {
guard: {
refreshing: boolean;
refreshQueue: ((token: string | null) => void)[];
};
}

View File

@ -12,7 +12,6 @@ export const axios = Axios.create({
}, },
}); });
let isRefreshing = false;
let refreshQueue: ((token: string | null) => void)[] = []; let refreshQueue: ((token: string | null) => void)[] = [];
const waitForTokenRefresh = () => { const waitForTokenRefresh = () => {
@ -60,7 +59,7 @@ const refreshToken = async (
} finally { } finally {
localStorage.removeItem("refreshing"); localStorage.removeItem("refreshing");
loadAccounts?.(); loadAccounts?.();
isRefreshing = false; window.guard.refreshing = false;
} }
}; };
@ -74,8 +73,9 @@ axios.interceptors.request.use(
return request; return request;
} }
if (!isRefreshing) { if (!window.guard.refreshing) {
isRefreshing = true; console.log(`request to ${request.url} is refreshing token`);
window.guard.refreshing = true;
try { try {
const { access } = await refreshToken( const { access } = await refreshToken(
account!.accountId, account!.accountId,
@ -87,7 +87,9 @@ axios.interceptors.request.use(
throw err; throw err;
} }
} else { } else {
console.log(`request to ${request.url} is waiting for token`);
token = await waitForTokenRefresh(); token = await waitForTokenRefresh();
console.log(`request to ${request.url} waited for token:`, token);
} }
if (!token) { if (!token) {

View File

@ -4,6 +4,13 @@ import App from "./App";
import "./index.css"; import "./index.css";
import { OAuthProvider } from "./context/oauth/provider"; import { OAuthProvider } from "./context/oauth/provider";
if (typeof window.guard !== "object") {
window.guard = {
refreshing: false,
refreshQueue: [],
};
}
const root = document.getElementById("root")!; const root = document.getElementById("root")!;
createRoot(root).render( createRoot(root).render(

View File

@ -25,5 +25,5 @@
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true "noUncheckedSideEffectImports": true
}, },
"include": ["src"] "include": ["src", "globals.d.ts"]
} }