11import { instance } from "@/api" ;
2+ import { useConnectionStore } from "@/store/useConnectionStore" ;
23import { TokenRefresh , User } from "@/types/auth" ;
3- import axios from "axios" ;
4+ import { logOnDev } from "@/utils/logging" ;
5+ import axios , { AxiosError , AxiosResponse } from "axios" ;
46
5- export const instanceForRefresh = axios . create ( {
7+ export const instanceForAuth = axios . create ( {
68 baseURL : import . meta. env . VITE_APP_API_SERVER_BASE_URL ,
79 timeout : 3000 ,
810 withCredentials : true ,
@@ -11,8 +13,41 @@ export const instanceForRefresh = axios.create({
1113 } ,
1214} ) ;
1315
16+ instanceForAuth . interceptors . response . use (
17+ ( response : AxiosResponse ) => {
18+ const { method, url } = response . config ;
19+ const { status } = response ;
20+
21+ logOnDev ( `🚀 [API Response] ${ method ?. toUpperCase ( ) } ${ url } | Response ${ status } ` ) ;
22+
23+ return response ;
24+ } ,
25+ async ( error : AxiosError | Error ) => {
26+ if ( axios . isAxiosError ( error ) ) {
27+ logOnDev ( `🚨 [API ERROR] ${ error . message } ` ) ;
28+
29+ if ( ! error . response ) {
30+ return Promise . reject ( error ) ;
31+ }
32+
33+ if ( error . response . status === 401 ) {
34+ try {
35+ await signOut ( ) ;
36+ } catch ( error ) {
37+ logOnDev ( `🚨 [API ERROR] ${ error . message } ` ) ;
38+ } finally {
39+ useConnectionStore . getState ( ) . logout ( ) ;
40+ location . href = "/" ;
41+ }
42+ }
43+ return Promise . reject ( error ) ;
44+ }
45+ logOnDev ( `🚨 [API ERROR] ${ error . message } ` ) ;
46+ } ,
47+ ) ;
48+
1449export const tokenRefresh = async ( ) : Promise < TokenRefresh > => {
15- const { data } = await instanceForRefresh . post ( "/auth/refresh" , { } , { withCredentials : true } ) ;
50+ const { data } = await instanceForAuth . post ( "/auth/refresh" , { } , { withCredentials : true } ) ;
1651 return data ;
1752} ;
1853
@@ -22,5 +57,5 @@ export const getUser = async (): Promise<User> => {
2257} ;
2358
2459export const signOut = async ( ) => {
25- return instance . post ( "/auth/logout" ) ;
60+ return instanceForAuth . post ( "/auth/logout" ) ;
2661} ;
0 commit comments