From 97da6b43c141a2e3d95daeb4a1313958e2e3fe0b Mon Sep 17 00:00:00 2001 From: hamster1963 <1410514192@qq.com> Date: Wed, 25 Dec 2024 11:18:16 +0800 Subject: [PATCH] feat: refresh token --- src/components/Header.tsx | 1 + src/lib/nezha-api.ts | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 1806c08..8ab54e4 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -145,6 +145,7 @@ function DashboardLink() { queryFn: () => fetchLoginUser(), refetchOnMount: true, refetchOnWindowFocus: true, + refetchInterval: 1000 * 60 * 1, }) return ( diff --git a/src/lib/nezha-api.ts b/src/lib/nezha-api.ts index 0570d21..e26e653 100644 --- a/src/lib/nezha-api.ts +++ b/src/lib/nezha-api.ts @@ -1,5 +1,7 @@ import { LoginUserResponse, MonitorResponse, ServerGroupResponse, ServiceResponse, SettingResponse } from "@/types/nezha-api" +let lastestRefreshTokenAt = 0 + export const fetchServerGroup = async (): Promise => { const response = await fetch("/api/v1/server-group") const data = await response.json() @@ -15,6 +17,13 @@ export const fetchLoginUser = async (): Promise => { if (data.error) { throw new Error(data.error) } + + // auto refresh token + if (document.cookie && (!lastestRefreshTokenAt || Date.now() - lastestRefreshTokenAt > 1000 * 60 * 60)) { + lastestRefreshTokenAt = Date.now() + fetch("/api/v1/refresh-token") + } + return data }