|
| 1 | +import axios from "axios"; |
| 2 | + |
| 3 | +import { PATH } from "@/routes/paths"; |
| 4 | +import { useAuthStore } from "@/stores/useAuthStore"; |
| 5 | +import type { ApiResponse } from "@/types/api"; |
| 6 | +import type { AuthTokenResponse } from "@/types/auth/auth"; |
| 7 | + |
| 8 | +const BASE_CONFIG = { |
| 9 | + baseURL: `${import.meta.env.VITE_API_BASE_URL}/api/v1`, |
| 10 | + headers: { "Content-Type": "application/json" }, |
| 11 | + timeout: 10000, |
| 12 | +}; |
| 13 | + |
| 14 | +// 토큰이 필요 없는 요청 — 로그인, 회원가입, 토큰 재발급 |
| 15 | +export const publicInstance = axios.create(BASE_CONFIG); |
| 16 | + |
| 17 | +// 토큰이 필요한 요청 — 헤더 자동 첨부, 401이면 재발급 후 재시도 |
| 18 | +export const authInstance = axios.create(BASE_CONFIG); |
| 19 | + |
| 20 | +authInstance.interceptors.request.use((config) => { |
| 21 | + const { accessToken } = useAuthStore.getState(); |
| 22 | + if (accessToken) { |
| 23 | + config.headers.Authorization = `Bearer ${accessToken}`; |
| 24 | + } |
| 25 | + |
| 26 | + return config; |
| 27 | +}); |
| 28 | + |
| 29 | +let reissuePromise: Promise<string> | null = null; |
| 30 | + |
| 31 | +const reissueAccessToken = async () => { |
| 32 | + const { refreshToken } = useAuthStore.getState(); |
| 33 | + if (!refreshToken) return null; |
| 34 | + |
| 35 | + reissuePromise ??= publicInstance |
| 36 | + .post<ApiResponse<AuthTokenResponse>>("/auth/reissue", { refreshToken }) |
| 37 | + .then((response) => { |
| 38 | + const tokens = response.data.data; |
| 39 | + useAuthStore.getState().setTokens(tokens); |
| 40 | + |
| 41 | + return tokens.accessToken; |
| 42 | + }) |
| 43 | + .finally(() => { |
| 44 | + reissuePromise = null; |
| 45 | + }); |
| 46 | + |
| 47 | + return reissuePromise.catch(() => null); |
| 48 | +}; |
| 49 | + |
| 50 | +authInstance.interceptors.response.use( |
| 51 | + (response) => response, |
| 52 | + async (error) => { |
| 53 | + const status = error.response?.status; |
| 54 | + const originRequest = error.config; |
| 55 | + |
| 56 | + if (status === 401 && originRequest) { |
| 57 | + if (!originRequest.isRetried) { |
| 58 | + originRequest.isRetried = true; |
| 59 | + |
| 60 | + const accessToken = await reissueAccessToken(); |
| 61 | + if (accessToken) { |
| 62 | + originRequest.headers.Authorization = `Bearer ${accessToken}`; |
| 63 | + return authInstance(originRequest); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + useAuthStore.getState().clearAuth(); |
| 68 | + |
| 69 | + if (window.location.pathname !== PATH.LOGIN) { |
| 70 | + window.location.replace(PATH.LOGIN); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return Promise.reject(error); |
| 75 | + } |
| 76 | +); |
0 commit comments