Skip to content

Commit 59e6b0f

Browse files
committed
pref: improve fetch api
1 parent 24a7311 commit 59e6b0f

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

src/config/Fetcher.ts

+47-3
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,46 @@ function createAuthAxios(baseURL: string): AxiosInstance {
4343
return instanceAxios
4444
}
4545

46+
function createDefaultAxios(baseURL: string): AxiosInstance {
47+
const instanceAxios = axios.create({
48+
baseURL,
49+
})
50+
51+
instanceAxios.interceptors.response.use(
52+
function onSuccess(response) {
53+
return response
54+
},
55+
function onError(error: AxiosError) {
56+
const statusCode = get(error, 'response.status', null)
57+
const message = get(error, 'response.data.message', null)
58+
59+
if (statusCode === 401) {
60+
console.log('Unauhtorized')
61+
throw new ResponseError.Unauthorized(message)
62+
}
63+
64+
if (statusCode === 400) {
65+
console.log('Bad Request')
66+
throw new ResponseError.BadRequest(message)
67+
}
68+
69+
if (statusCode === 404) {
70+
console.log('Not Found')
71+
throw new ResponseError.NotFound(message)
72+
}
73+
74+
const handleError = error?.response?.headers?.handleError
75+
if (!handleError || !handleError(error)) {
76+
console.log(error.message)
77+
throw new ResponseError.BadRequest(error.message)
78+
}
79+
return Promise.reject(error)
80+
}
81+
)
82+
83+
return instanceAxios
84+
}
85+
4686
class FetchApi {
4787
private axiosDefault: AxiosInstance
4888

@@ -58,17 +98,21 @@ class FetchApi {
5898
this.baseUri = baseUri
5999
}
60100

101+
/**
102+
* axios instance default
103+
*/
61104
get default(): AxiosInstance {
62105
if (!this.axiosDefault) {
63-
this.axiosDefault = axios.create({
64-
baseURL: this.baseUri,
65-
})
106+
this.axiosDefault = createDefaultAxios(this.baseUri)
66107
return this.axiosDefault
67108
}
68109

69110
return this.axiosDefault
70111
}
71112

113+
/**
114+
* axios instance with auth token
115+
*/
72116
get withAuth(): AxiosInstance {
73117
if (!this.axiosToken) {
74118
this.axiosToken = createAuthAxios(this.baseUri)

0 commit comments

Comments
 (0)