feat(web): integrate session management and improve API error handling
This commit is contained in:
@@ -1,12 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "@heroui/react";
|
||||
import { signOut, useSession } from "@/lib/auth-client";
|
||||
import { APIError } from "@/lib/api";
|
||||
|
||||
/** 监听 better-auth 会话变为 null(服务端过期/异地登出等场景)*/
|
||||
function SessionMonitor({ onExpired }: { onExpired: () => void }) {
|
||||
const { data: session, isPending } = useSession();
|
||||
const wasLoggedIn = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPending) return;
|
||||
if (session) {
|
||||
wasLoggedIn.current = true;
|
||||
} else if (wasLoggedIn.current) {
|
||||
wasLoggedIn.current = false;
|
||||
onExpired();
|
||||
}
|
||||
}, [session, isPending, onExpired]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ReactQueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const isHandling = useRef(false);
|
||||
|
||||
const handleExpired = useCallback(async () => {
|
||||
if (isHandling.current) return;
|
||||
isHandling.current = true;
|
||||
try {
|
||||
await signOut({ fetchOptions: { credentials: "include" } });
|
||||
} catch {
|
||||
// ignore sign-out errors
|
||||
}
|
||||
toast.warning("登录已过期,请重新登录");
|
||||
router.push("/login");
|
||||
}, [router]);
|
||||
|
||||
// Stable ref so the QueryClient (created once) always calls the latest handler
|
||||
const handleExpiredRef = useRef(handleExpired);
|
||||
handleExpiredRef.current = handleExpired;
|
||||
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
queryCache: new QueryCache({
|
||||
onError: (error) => {
|
||||
if (error instanceof APIError && error.status === 401) {
|
||||
handleExpiredRef.current();
|
||||
}
|
||||
},
|
||||
}),
|
||||
mutationCache: new MutationCache({
|
||||
onError: (error) => {
|
||||
if (error instanceof APIError && error.status === 401) {
|
||||
handleExpiredRef.current();
|
||||
}
|
||||
},
|
||||
}),
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 10_000,
|
||||
@@ -14,5 +69,11 @@ export function ReactQueryProvider({ children }: { children: React.ReactNode })
|
||||
},
|
||||
}),
|
||||
);
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SessionMonitor onExpired={handleExpired} />
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "@heroui/react";
|
||||
import { useSession, signOut } from "@/lib/auth-client";
|
||||
|
||||
export function SessionWatcher() {
|
||||
const router = useRouter();
|
||||
const { data: session, isPending } = useSession();
|
||||
const wasLoggedIn = useRef(false);
|
||||
const isHandling = useRef(false);
|
||||
|
||||
const handleExpired = useCallback(async () => {
|
||||
if (isHandling.current) return;
|
||||
isHandling.current = true;
|
||||
try {
|
||||
await signOut({ fetchOptions: { credentials: "include" } });
|
||||
} catch {
|
||||
// ignore sign-out errors
|
||||
}
|
||||
toast.warning("登录已过期,请重新登录");
|
||||
router.push("/login");
|
||||
}, [router]);
|
||||
|
||||
// Detect session becoming null after being valid (e.g. server-side expiry)
|
||||
useEffect(() => {
|
||||
if (isPending) return;
|
||||
if (session) {
|
||||
wasLoggedIn.current = true;
|
||||
} else if (wasLoggedIn.current) {
|
||||
handleExpired();
|
||||
}
|
||||
}, [session, isPending, handleExpired]);
|
||||
|
||||
// Detect 401 responses from the API (dispatched by apiFetch)
|
||||
useEffect(() => {
|
||||
const handler = () => handleExpired();
|
||||
window.addEventListener("session:expired", handler);
|
||||
return () => window.removeEventListener("session:expired", handler);
|
||||
}, [handleExpired]);
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user