Skip to content

Commit 78f802d

Browse files
committed
refactor: config fetch api
1 parent af38cb7 commit 78f802d

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

src/config/Fetcher.ts

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,60 @@
11
/* eslint-disable no-unused-vars */
2-
import axios, { AxiosInstance } from 'axios'
2+
import axios, { AxiosError, AxiosInstance } from 'axios'
3+
import { get } from 'lodash'
4+
import ResponseError from 'modules/Response/ResponseError'
5+
6+
function createAuthAxios(baseURL: string): AxiosInstance {
7+
const instanceAxios = axios.create({
8+
baseURL,
9+
})
10+
11+
instanceAxios.interceptors.request.use((config) => {
12+
const curConfig = { ...config }
13+
14+
// ALWAYS READ UPDATED TOKEN
15+
try {
16+
curConfig.headers.Authorization = localStorage.getItem('token')
17+
} catch (e) {
18+
console.log(e)
19+
}
20+
return curConfig
21+
})
22+
23+
instanceAxios.interceptors.response.use(
24+
function onSuccess(response) {
25+
return response
26+
},
27+
function onError(error: AxiosError) {
28+
const status = get(error, 'response.status', null)
29+
if (status === 401) {
30+
console.log('Unauhtorized')
31+
return Promise.reject(error)
32+
}
33+
34+
const handleError = error?.response?.headers?.handleError
35+
if (!handleError || !handleError(error)) {
36+
console.log(error.message)
37+
throw new ResponseError.BadRequest(error.message)
38+
}
39+
return Promise.reject(error)
40+
}
41+
)
42+
43+
return instanceAxios
44+
}
345

446
class FetchApi {
547
private axiosDefault: AxiosInstance
648

49+
private axiosToken: AxiosInstance
50+
751
private baseUri: string
852

953
constructor(baseUri: string) {
1054
// @ts-ignore
1155
this.axiosDefault = null
56+
// @ts-ignore
57+
this.axiosToken = null
1258
this.baseUri = baseUri
1359
}
1460

@@ -22,6 +68,14 @@ class FetchApi {
2268

2369
return this.axiosDefault
2470
}
71+
72+
get withAuth(): AxiosInstance {
73+
if (!this.axiosToken) {
74+
this.axiosToken = createAuthAxios(this.baseUri)
75+
return this.axiosToken
76+
}
77+
return this.axiosToken
78+
}
2579
}
2680

2781
export default FetchApi

0 commit comments

Comments
 (0)