-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxios.js
57 lines (52 loc) · 1.54 KB
/
axios.js
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
import * as axiosLib from 'axios'
import { API_URL } from '@/consts'
export default function ({ $axios, store, redirect }) {
$axios.onResponseError(async (error) => {
store.commit('updateSnackbar', {
state: true,
message: error.response?.data?.message,
type: 'error',
data: error.response?.data,
apiError: true,
code: error.response?.status
})
const originalRequest = error.config
if (
error.response.status === 401 &&
error.config &&
!error.config._isRetry
) {
originalRequest._isRetry = true
try {
const { data: newToken } = await axiosLib.get(`${API_URL}refresh`, {
withCredentials: true
})
localStorage.setItem('auth', JSON.stringify(newToken.tokens))
store.commit('auth/updateAuth', newToken.tokens)
store.commit('auth/setLoggedIn', true)
store.commit('auth/setCurrentUser', newToken.user)
return $axios.request(originalRequest)
} catch (e) {
store.commit('updateSnackbar', {
state: true,
message: 'You should log in again',
type: 'info',
apiError: false
})
redirect('/')
}
}
throw error
})
$axios.onRequest((config) => {
if (localStorage.auth) {
const accessToken = JSON.parse(localStorage.auth).accessToken
if (!config.headers.authorization && accessToken) {
config.headers.authorization = `Bearer ${
JSON.parse(localStorage.auth).accessToken
}`
}
}
return config
})
}