11import axios , { AxiosError , AxiosRequestConfig } from "axios" ;
22import { config } from "@/config" ;
33import { BaseQueryFn } from "@reduxjs/toolkit/query" ;
4+ import { clearUser , setUser } from "@/features/user/slice" ;
45
5- console . log ( config . apiUrl ) ;
66const instance = axios . create ( {
77 baseURL : config . apiUrl ,
88 timeout : 5_000 ,
@@ -17,6 +17,11 @@ const instance = axios.create({
1717 ] ,
1818} ) ;
1919
20+ type HttpBaseQueryError = {
21+ status : number ;
22+ data : { message : string } ;
23+ } ;
24+
2025const httpBaseQuery =
2126 (
2227 { baseUrl } : { baseUrl : string } = { baseUrl : "" } ,
@@ -29,9 +34,9 @@ const httpBaseQuery =
2934 headers ?: AxiosRequestConfig [ "headers" ] ;
3035 } ,
3136 unknown ,
32- unknown
37+ HttpBaseQueryError
3338 > =>
34- async ( { url, method, data, params, headers } ) => {
39+ async ( { url, method, data, params, headers } , api ) => {
3540 try {
3641 const result = await instance ( {
3742 url : baseUrl + url ,
@@ -40,18 +45,54 @@ const httpBaseQuery =
4045 params,
4146 headers,
4247 } ) ;
48+
4349 return {
4450 data : result ,
4551 } ;
4652 } catch ( axiosError ) {
4753 const error = axiosError as AxiosError ;
48- return {
49- error : {
50- status : error . status ,
51- data : error . response ?. data || error . message ,
52- } ,
53- } ;
54+
55+ if ( error . response ?. status != 401 ) {
56+ return {
57+ error : {
58+ status : error . response ?. status ?? 500 ,
59+ data : ( error . response ?. data as { message : string } ) || {
60+ message : error . message ,
61+ } ,
62+ } ,
63+ } ;
64+ }
65+
66+ try {
67+ const response = await instance . post ( "/auth/refresh" ) ;
68+ api . dispatch ( setUser ( response . data ) ) ;
69+
70+ const retryResult = await instance ( {
71+ url : baseUrl + url ,
72+ method,
73+ data,
74+ params,
75+ headers,
76+ } ) ;
77+
78+ return {
79+ data : retryResult . data ,
80+ } ;
81+ } catch ( axiosError ) {
82+ const error = axiosError as AxiosError ;
83+ api . dispatch ( clearUser ( ) ) ;
84+
85+ return {
86+ error : {
87+ status : error . response ?. status ?? 500 ,
88+ data : ( error . response ?. data as { message : string } ) || {
89+ message : error . message ,
90+ } ,
91+ } ,
92+ } ;
93+ }
5494 }
5595 } ;
5696
5797export { instance , httpBaseQuery } ;
98+ export type { HttpBaseQueryError } ;
0 commit comments