Files
o2o-weather/mobile/src/lib/auth.tsx
T
minaChoi 86a0ea26ca feat: 회원 탈퇴 (DELETE /v1/auth/me, 웹·앱 내 정보 시트 '탈퇴하기')
- 계정과 남긴 댓글·좋아요·저장을 한 트랜잭션으로 지우고 게시물·댓글 수를 맞춘다
- 로그아웃·탈퇴 때 내 정보 캐시를 먼저 버려 401 로 로그인 창이 뜨지 않게
- 탈퇴 테스트 추가, 공용 API 클라이언트 다시 생성
2026-10-19 11:33:05 +09:00

47 lines
2.2 KiB
TypeScript

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<AuthApi | null>(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 <AuthContext value={api}>{children}</AuthContext>;
}