优化 Convex URL 检查和认证 token 获取逻辑
This commit is contained in:
@@ -3,6 +3,9 @@ import { ConvexClient, AuthTokenFetcher, ConvexHttpClient } from "convex/browser
|
||||
const url = localStorage.getItem("CONVEX_URL") || 'https://convex.kevisual.cn'
|
||||
const client = new ConvexClient(url!);
|
||||
const httpClient = new ConvexHttpClient(url!);
|
||||
if (url !== 'https://convex.kevisual.cn') {
|
||||
console.warn("当前使用的Convex URL为:", url, "请确保这是你想要连接的Convex实例");
|
||||
}
|
||||
export const initConvex = async () => {
|
||||
const getToken = async () => {
|
||||
const token = localStorage.getItem("token");
|
||||
@@ -16,12 +19,21 @@ export const initConvex = async () => {
|
||||
return null;
|
||||
}
|
||||
const authTokenFetcher: AuthTokenFetcher = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
||||
if (forceRefreshToken) {
|
||||
const token = await getToken();
|
||||
// console.log("fetch got token:", token);
|
||||
return token;
|
||||
// 无论是否强制刷新,都优先使用缓存(除非缓存无效)
|
||||
if (!forceRefreshToken) {
|
||||
const cachedToken = sessionStorage.getItem("convex_token");
|
||||
if (cachedToken) {
|
||||
return cachedToken;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
// 没有缓存或强制刷新时,获取新 token
|
||||
const token = await getToken();
|
||||
if (token) {
|
||||
sessionStorage.setItem("convex_token", token);
|
||||
}
|
||||
return token;
|
||||
|
||||
}
|
||||
client.setAuth(authTokenFetcher, (isAuthenticated) => {
|
||||
console.log("Auth isAuthenticated:", isAuthenticated);
|
||||
|
||||
Reference in New Issue
Block a user