import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'; import { meOptions, meQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'; import type { Me } from '@nalssigak/shared/api/client/types.gen'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { createContext, use, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'; /** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */ export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }; const AuthContext = createContext(null); export function useAuth() { const ctx = use(AuthContext); if (!ctx) throw new Error('useAuth must be used inside AuthProvider'); return ctx; } const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb()); /** 서버에서 이 계정의 토큰을 모두 무효로 만들고(실패해도) 기기 토큰을 지운다 */ const logout = () => { void logoutOnServer({ throwOnError: false }).finally(clearTokens); }; export function AuthProvider({ children }: { children: ReactNode }) { const token = useSyncExternalStore(subscribe, getAccessToken); const queryClient = useQueryClient(); const me = useQuery({ ...meOptions(), enabled: !!token }); // 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다 // 로그아웃·탈퇴 땐 내 정보 캐시를 먼저 버린다. 남겨 두면 다시 받다가 401 이 나서 로그인 창이 뜬다 useEffect( () => subscribeAuth((reason) => { if (reason !== 'change') return; if (!getAccessToken()) queryClient.removeQueries({ queryKey: meQueryKey() }); void queryClient.invalidateQueries(); }), [queryClient], ); const mePending = !!token && me.isPending; const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending]); return {children}; }