-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathhttp.init.js
More file actions
44 lines (38 loc) · 1.23 KB
/
http.init.js
File metadata and controls
44 lines (38 loc) · 1.23 KB
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
/**
* HTTP request layer
* if auth is required return patched axios instance(with access token in headers)
* else return clear axios instance
*/
import axios from 'axios'
import { AuthService } from '@/services/auth.service'
import { API_URL } from '../.env'
export class Http {
constructor (status) {
this.isAuth = status && status.auth ? status.auth : false
this.instance = axios.create({
baseURL: API_URL
})
return this.init()
}
init () {
if (this.isAuth) {
this.instance.interceptors.request.use(request => {
request.headers.authorization = AuthService.getBearer()
// if access token expired and refreshToken is exist >> go to API and get new access token
if (AuthService.isAccessTokenExpired() && AuthService.hasRefreshToken()) {
return AuthService.debounceRefreshTokens()
.then(response => {
AuthService.setBearer(response.data.accessToken)
request.headers.authorization = AuthService.getBearer()
return request
}).catch(error => Promise.reject(error))
} else {
return request
}
}, error => {
return Promise.reject(error)
})
}
return this.instance
}
}