fix: window scoped state for token refresh
This commit is contained in:
6
web/globals.d.ts
vendored
Normal file
6
web/globals.d.ts
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
interface Window {
|
||||||
|
guard: {
|
||||||
|
refreshing: boolean;
|
||||||
|
refreshQueue: ((token: string | null) => void)[];
|
||||||
|
};
|
||||||
|
}
|
@ -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) {
|
||||||
|
@ -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(
|
||||||
|
@ -25,5 +25,5 @@
|
|||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"noUncheckedSideEffectImports": true
|
"noUncheckedSideEffectImports": true
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src", "globals.d.ts"]
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user