forked from user-ank/devlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
for later.txt
51 lines (41 loc) · 1.67 KB
/
for later.txt
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
import { PrivateAPI } from "../../api";
import { useEffect } from "react";
import useRefreshToken from "./useRefreshToken";
import { useAuth } from "../../context/auth";
function useAxiosPrivate(abortSignal) {
const refresh = useRefreshToken();
const { user } = useAuth();
const interceptController = new AbortController();
useEffect(() => {
const requestIntercept = PrivateAPI.interceptors.request.use(
config => {
if(!config.headers['Authorization']){
config.headers['Authorization'] = `Bearer ${user?.accessToken}`;
}
return config;
}, (err) => Promise.reject(err),
{ signal: interceptController.signal }
);
const responseIntercept = PrivateAPI.interceptors.response.use(
response => response,
async (err) =>{
const prevRequest = err?.config;
if(err?.response.status === 500 && !prevRequest?.sent){
prevRequest.sent = true;
const newAccessToken = await refresh();
prevRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
return PrivateAPI(prevRequest);
}
return Promise.reject(err);
},
{ signal: interceptController.signal }
);
return () => {
interceptController.abort();
PrivateAPI.interceptors.request.eject(requestIntercept);
PrivateAPI.interceptors.response.eject(responseIntercept);
}
},[user, refresh, abortSignal])
return PrivateAPI;
}
export default useAxiosPrivate