diff --git a/src/pages/auth/hooks/index.ts b/src/pages/auth/hooks/index.ts new file mode 100644 index 0000000..660cd77 --- /dev/null +++ b/src/pages/auth/hooks/index.ts @@ -0,0 +1 @@ +export * from './use-api-query'; diff --git a/src/pages/auth/hooks/use-api-query.ts b/src/pages/auth/hooks/use-api-query.ts new file mode 100644 index 0000000..44302c2 --- /dev/null +++ b/src/pages/auth/hooks/use-api-query.ts @@ -0,0 +1,55 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { queryLogin } from '@/modules/query'; +import { toast } from 'sonner'; +import type { UserInfo } from '../store'; + +export const authQueryKeys = { + me: ['auth', 'me'] as const, + token: ['auth', 'token'] as const, +} as const; + +export const useMe = () => { + return useQuery({ + queryKey: authQueryKeys.me, + queryFn: async () => { + const res = await queryLogin.getMe(); + if (res.code === 200) { + return res.data; + } + throw new Error(res.message || 'Failed to fetch user info'); + }, + staleTime: 1000 * 60 * 5, // 5 minutes + }); +}; + +export const useSwitchOrg = () => { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (username?: string) => { + const res = await queryLogin.switchUser(username || ''); + if (res.code === 200) { + return res.data; + } + throw new Error(res.message || 'Switch failed'); + }, + onSuccess: () => { + toast.success('切换成功'); + queryClient.invalidateQueries({ queryKey: authQueryKeys.me }); + setTimeout(() => { + window.location.reload(); + }, 1000); + }, + onError: (error) => { + toast.error(error.message || '请求失败'); + }, + }); +}; + +export const useGetToken = () => { + return useQuery({ + queryKey: authQueryKeys.token, + queryFn: () => queryLogin.getToken(), + staleTime: Infinity, + }); +}; diff --git a/src/pages/auth/index.tsx b/src/pages/auth/index.tsx index ac827c7..de5fc95 100644 --- a/src/pages/auth/index.tsx +++ b/src/pages/auth/index.tsx @@ -5,6 +5,7 @@ import { LogIn, LockKeyhole } from "lucide-react" export { BaseHeader } from './modules/BaseHeader' import { useMemo } from 'react'; import { useLocation, useNavigate } from '@tanstack/react-router'; +import { useMe } from "./hooks" type Props = { @@ -26,6 +27,8 @@ export const AuthProvider = ({ children, mustLogin }: Props) => { return store.openLinkList.some(item => location.pathname.startsWith(item)) }, [location.pathname]) const loginUrl = '/root/login/?redirect=' + encodeURIComponent(window.location.href); + const me = useMe() + console.log('me', me, me.error); if (mustLogin && !store.me && !isOpen) { return (