feat(frontend): TanStack Query 기반 apis 레이어 추가

- auth/negotiation 도메인별 api/keys/queries/mutations/type 5파일 구조
- axios 인스턴스: access token 주입, 434 만료 시 refresh 자동 재발급(단일 비행)
  후 원요청 재시도, 433/435/1203(TOKEN_REVOKED) 시 세션 종료 처리
- HTTP 200 + result.success=false 비즈니스 에러를 ApiError 로 변환,
  에러코드별 한국어 메시지 맵(getApiErrorMessage) 제공
- 토큰 localStorage 저장소(tokenStorage)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Opus 4.8 committed 2026-06-18 13:12:07 +09:00
1 parent 2480a47efe
commit a867daa98f
16 files changed
+629

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
// 인증 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
// refresh_token 재발급은 http.ts 인터셉터가 자동 처리하므로 여기서 노출하지 않는다.
import { http } from '@/apis/http'
import type {
CreateAccountRequest,
CreateAccountResponse,
LoginRequest,
LoginResponse,
LogoutResponse,
MeResponse,
} from './auth.type'
export const authApi = {
/** POST /v1/auth/login — ID/PW 로 로그인, access/refresh 토큰 발급 */
login: async (body: LoginRequest): Promise<LoginResponse> => {
const res = await http.post<LoginResponse>('/v1/auth/login', body)
return res.data
},
/** POST /v1/auth/create — 신규 공급사 유저 계정 생성 */
createAccount: async (body: CreateAccountRequest): Promise<CreateAccountResponse> => {
const res = await http.post<CreateAccountResponse>('/v1/auth/create', body)
return res.data
},
/** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */
me: async (): Promise<MeResponse> => {
const res = await http.get<MeResponse>('/v1/auth/me')
return res.data
},
/** POST /v1/auth/logout — 서버측 토큰 폐기(단일 세션) */
logout: async (): Promise<LogoutResponse> => {
const res = await http.post<LogoutResponse>('/v1/auth/logout')
return res.data
},
}
+5
View File
@@ -0,0 +1,5 @@
// 인증 도메인의 TanStack Query 키 팩토리.
export const authKeys = {
all: ['auth'] as const,
me: () => [...authKeys.all, 'me'] as const,
}
+55
View File
@@ -0,0 +1,55 @@
// 인증 도메인의 변경(useMutation) 훅.
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { tokenStorage } from '@/apis/tokenStorage'
import { authApi } from './auth.api'
import { authKeys } from './auth.keys'
import type { CreateAccountRequest, LoginResponse } from './auth.type'
/** 로그인 폼이 다루는 파라미터 (UI 친화적인 camelCase) */
export interface LoginParams {
id: string
password: string
}
/**
* 로그인: 성공 시 토큰을 저장하고 me 캐시를 무효화한다.
*/
export function useLoginMutation() {
const queryClient = useQueryClient()
return useMutation<LoginResponse, Error, LoginParams>({
mutationFn: async ({ id, password }) => {
const data = await authApi.login({ id, pw: password })
tokenStorage.setTokens(data.access_token, data.refresh_token)
return data
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: authKeys.me() })
},
})
}
/**
* 로그아웃: 서버 토큰 폐기를 시도하고(실패해도) 로컬 토큰/캐시를 비운다.
*/
export function useLogoutMutation() {
const queryClient = useQueryClient()
return useMutation<void, Error, void>({
mutationFn: async () => {
try {
await authApi.logout()
} finally {
tokenStorage.clear()
}
},
onSettled: () => {
queryClient.clear()
},
})
}
/** 공급사 유저 계정 생성 */
export function useCreateAccountMutation() {
return useMutation({
mutationFn: (body: CreateAccountRequest) => authApi.createAccount(body),
})
}
+20
View File
@@ -0,0 +1,20 @@
// 인증 도메인의 조회(useQuery) 훅.
import { useQuery } from '@tanstack/react-query'
import { tokenStorage } from '@/apis/tokenStorage'
import { authApi } from './auth.api'
import { authKeys } from './auth.keys'
import { toAuthUser } from './auth.type'
/**
* 현재 로그인 유저 정보 조회.
* 토큰이 있을 때만 활성화되며, AuthUser(카멜케이스)로 가공해 반환한다.
*/
export function useMeQuery() {
return useQuery({
queryKey: authKeys.me(),
queryFn: authApi.me,
enabled: tokenStorage.hasToken(),
staleTime: 5 * 60 * 1000, // 5분
select: toAuthUser,
})
}
+91
View File
@@ -0,0 +1,91 @@
// 인증 API 의 요청/응답 타입.
// 와이어 포맷은 백엔드(snake_case)를 그대로 미러링한다.
import type { ApiResult } from '@/apis/types'
/** 유저 권한 (supplier_users.role) */
export const UserRole = {
USER: 1,
MANAGER: 2,
} as const
export type UserRole = (typeof UserRole)[keyof typeof UserRole]
export const USER_ROLE_LABEL: Record<UserRole, string> = {
[UserRole.USER]: '일반',
[UserRole.MANAGER]: '매니저',
}
// --- 로그인 ---------------------------------------------------------------
export interface LoginRequest {
id: string
pw: string
}
export interface LoginResponse {
result: ApiResult
su_id: string
name: string
supplier_id: string
supplier_name: string
role: number
access_token: string
refresh_token: string
}
// --- 계정 생성 ------------------------------------------------------------
export interface CreateAccountRequest {
supplier_id: string
id: string
pw: string
name?: string
email?: string
contact_number?: string
role?: number
}
export interface CreateAccountResponse {
result: ApiResult
su_id: string
}
// --- 토큰 재발급 ----------------------------------------------------------
export interface RefreshTokenResponse {
result: ApiResult
access_token: string
}
// --- 내 정보 (GET /v1/auth/me) -------------------------------------------
export interface MeResponse {
result: ApiResult
su_id: string
id: string
name: string
supplier_id: string
supplier_name: string
role: number
}
// --- 로그아웃 -------------------------------------------------------------
export interface LogoutResponse {
result: ApiResult
}
/** 앱에서 다루기 편한 현재 유저 형태 (MeResponse 에서 파생) */
export interface AuthUser {
suId: string
loginId: string
name: string
supplierId: string
supplierName: string
role: number
}
export function toAuthUser(res: MeResponse): AuthUser {
return {
suId: res.su_id,
loginId: res.id,
name: res.name,
supplierId: res.supplier_id,
supplierName: res.supplier_name,
role: res.role,
}
}
+11
View File
@@ -0,0 +1,11 @@
// 인증 API 모듈 공개 표면.
export { authApi } from './auth.api'
export { authKeys } from './auth.keys'
export { useMeQuery } from './auth.queries'
export {
useLoginMutation,
useLogoutMutation,
useCreateAccountMutation,
type LoginParams,
} from './auth.mutations'
export * from './auth.type'