-
Notifications
You must be signed in to change notification settings - Fork 0
/
axios-auto-token-refresh.ts
112 lines (87 loc) · 1.98 KB
/
axios-auto-token-refresh.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from "axios"
import { State } from "store/state"
import { Dispatch, Store } from "utils/bazaar"
import { refresh } from "actions/account";
const api = (store : Store<State>) =>
{
let config : AxiosRequestConfig = {
baseURL: `${SERVICE_URL}/api`
}
const state = store.getState()
if(state.actor.type === "loggedIn")
{
config = {
...config,
headers:
{
"Authorization": `Bearer ${state.actor.auth.access.token}`
}
}
}
const _api = axios.create(config)
//on auth catch response error
const enable401interceptor = () =>
{
const interceptor = _api.interceptors.response.use(
response => response,
async ( error: AxiosError ) =>
{
if(error.response == null)
throw error
if(error.response.status !== 401)
throw error
console.log("unauthenticated!")
// Unauthenticated
_api.interceptors.response.eject(interceptor)
const dtoToken = await refresh(store)
if(dtoToken.error)
throw error
const newConfig : AxiosRequestConfig = {
...error.config,
headers: {
...error.config.headers,
"Authorization" : `Bearer ${dtoToken.data}`
}
}
const response = await axios.request(newConfig)
enable401interceptor()
return response
}
)
}
enable401interceptor()
return _api
}
export default api
interface BaseApiResult
{
error: boolean
}
interface SuccessfulApiResult<T> extends BaseApiResult
{
error: false
data: T
}
interface UnsuccessfulApiResult extends BaseApiResult
{
error: true
code: number
}
export type ApiResult<T> = SuccessfulApiResult<T> | UnsuccessfulApiResult
export const transformApiError = (error: any) : UnsuccessfulApiResult =>
{
const err = error as AxiosError
if(err.response == null)
return { error: true, code: 0 }
return {
error: true,
code: err.response.data.Code
}
}
export const transformApiSuccess = <T>(data: T) : SuccessfulApiResult<T> =>
{
return {
error: false,
data
}
}