-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstance.ts
More file actions
78 lines (69 loc) Β· 2.54 KB
/
instance.ts
File metadata and controls
78 lines (69 loc) Β· 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import axios, { AxiosError } from 'axios'
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/features/auth/store/authStore'
export const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 15000, // 15μ΄
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
})
// μμ² μ token μΆκ°
axiosInstance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const { isLogin, accessToken } = useAuthStore.getState()
const token = isLogin ? accessToken : sessionStorage.getItem('anonymous_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => Promise.reject(error)
)
// μλ΅ interceptor
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response.data,
(error: AxiosError<{ code?: string; message?: string }>) => {
const code = error.response?.data?.code
const status = error.response?.status
const { isLogin, setLogout } = useAuthStore.getState()
const currentPath = window.location.pathname
if (code === 'COMMON-401' || status === 401) {
if (isLogin) {
// νμ λ‘κ·ΈμΈ ν ν° λ§λ£ λ§λ£ β λ‘κ·Έμμ + λ‘κ·ΈμΈ νμ΄μ§ μ΄λ
if (!['/login', '/login/callback'].includes(currentPath)) {
setLogout()
localStorage.setItem('show_expired_toast', 'true')
window.location.replace('/login')
}
return
}
// λΉνμ β μ΅λͺ
ν ν° μ¬λ°κΈ (λ‘κ·ΈμΈ/μ½λ°± νμ΄μ§λ μ μΈ)
if (!['/login', '/login/callback'].includes(currentPath)) {
return (async () => {
try {
const res = await axios.post(
`${import.meta.env.VITE_API_URL}/auth/anonymous`,
{},
{ withCredentials: true }
)
// μλ² μλ΅ νν νμΈ (string vs object)
const token = typeof res.data === 'string' ? res.data : res.data.token
sessionStorage.setItem('anonymous_token', token)
// μλ μμ² μ¬μλ
if (error.config) {
error.config.headers.Authorization = `Bearer ${token}`
return axiosInstance.request(error.config)
}
} catch (e) {
console.error('μ΅λͺ
ν ν° μ¬λ°κΈ μ€ν¨: ', e)
}
return Promise.reject(error)
})()
}
}
console.error('Axios Error: ', error.response ?? error)
return Promise.reject(error)
}
)