|
1 | 1 | import axios from 'axios'; |
| 2 | +import { useLayoutEffect } from 'react'; |
| 3 | + |
| 4 | +import useAuthStore from '@/stores/authStore'; |
| 5 | + |
| 6 | +import { getNewToken } from './auth'; |
2 | 7 |
|
3 | 8 | const client = axios.create({ |
4 | 9 | baseURL: import.meta.env.VITE_API_URL, |
5 | 10 | }); |
6 | 11 |
|
7 | | -client.interceptors.request.use( |
8 | | - (config) => { |
9 | | - const token = localStorage.getItem('authToken'); |
10 | | - if (token) { |
11 | | - config.headers['Authorization'] = `Bearer ${token}`; |
12 | | - } |
13 | | - return config; |
14 | | - }, |
15 | | - (error) => { |
16 | | - //TODO: 에러처리 |
17 | | - return Promise.reject(error); |
18 | | - }, |
19 | | -); |
| 12 | +// eslint-disable-next-line react-hooks/rules-of-hooks |
| 13 | + |
| 14 | +export const useAxiosIntercepter = () => { |
| 15 | + const { accessToken, setAccessToken } = useAuthStore(); |
| 16 | + const authIntercepter = client.interceptors.request.use( |
| 17 | + (config) => { |
| 18 | + config.headers.Authorization = |
| 19 | + accessToken && !config.headers['x-retry'] |
| 20 | + ? `Bearer ${accessToken}` |
| 21 | + : config.headers.Authorization; |
| 22 | + return config; |
| 23 | + }, |
| 24 | + (error) => { |
| 25 | + return Promise.reject(error); |
| 26 | + }, |
| 27 | + ); |
| 28 | + |
| 29 | + const refreshInterceptor = client.interceptors.response.use( |
| 30 | + (response) => response, |
| 31 | + async (error) => { |
| 32 | + const originalRequest = error.config; |
| 33 | + |
| 34 | + if ( |
| 35 | + (error.response.status === 401 || error.response.status === 403) && |
| 36 | + error.response.data.message === 'Unauthorized' |
| 37 | + ) { |
| 38 | + try { |
| 39 | + const response = await getNewToken(); |
| 40 | + setAccessToken(response?.data.accessToken); |
| 41 | + |
| 42 | + originalRequest.headers.Authorization = `Bearer ${response?.data.accessToken}`; |
| 43 | + originalRequest.headers['x-retry'] = true; |
| 44 | + |
| 45 | + return client(originalRequest); |
| 46 | + } catch { |
| 47 | + setAccessToken(''); |
| 48 | + } |
| 49 | + } |
| 50 | + return Promise.reject(error); |
| 51 | + }, |
| 52 | + ); |
| 53 | + |
| 54 | + useLayoutEffect(() => { |
| 55 | + return () => { |
| 56 | + client.interceptors.request.eject(authIntercepter); |
| 57 | + }; |
| 58 | + }, [accessToken]); |
| 59 | + |
| 60 | + useLayoutEffect(() => { |
| 61 | + return () => { |
| 62 | + client.interceptors.response.eject(refreshInterceptor); |
| 63 | + }; |
| 64 | + }, [accessToken]); |
| 65 | +}; |
20 | 66 |
|
21 | 67 | export default client; |
0 commit comments