Created
May 22, 2023 20:15
-
-
Save agjs/6e1a61490027ea42133c999d856681e1 to your computer and use it in GitHub Desktop.
axios twitch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-nocheck | |
import Axios from "axios"; | |
import { setupCache } from "axios-cache-interceptor"; | |
import { CUSTOM_ERRORS_ENUM } from "@Utils/constants"; | |
import { BASE_API_URL } from "@Services/constants"; | |
const axios = setupCache(Axios); | |
class Request { | |
constructor() { | |
this.client = axios.create({ | |
baseURL: BASE_API_URL, | |
withCredentials: import.meta.env.PROD | |
}); | |
this.setRequestInterceptor(); | |
this.setResponseInterceptor(); | |
} | |
getBaseConfig(request) { | |
return { | |
...request, | |
headers: { | |
"Content-Type": "application/json", | |
...request.headers | |
} | |
}; | |
} | |
setRequestInterceptor() { | |
this.client.interceptors.request.use( | |
async request => { | |
const baseConfig = this.getBaseConfig(request); | |
return baseConfig; | |
}, | |
error => { | |
return Promise.reject(error); | |
} | |
); | |
} | |
setResponseInterceptor() { | |
this.client.interceptors.response.use( | |
response => { | |
return response; | |
}, | |
error => { | |
if (error.response?.status === 500 && error.response.data?.reason === "AVATAR_UPLOAD_FAILED") { | |
throw error.response.data; | |
} | |
if (error.response?.status === 404) { | |
if (error.response.data.reason === CUSTOM_ERRORS_ENUM.THOUGHT_NOT_FOUND) { | |
throw error.response.data; | |
} | |
} | |
if (error.response?.status === 400) { | |
if (error.response.data.reason) { | |
throw error.response.data; | |
} | |
if (error.response.data.type === CUSTOM_ERRORS_ENUM.AJV_VALIDATION_ERROR || error.response.data.isCustomError) { | |
throw error.response.data; | |
} | |
} | |
throw error; | |
} | |
); | |
} | |
get(url) { | |
return this.client.get(url); | |
} | |
put(url, body) { | |
return this.client.put(url, body); | |
} | |
patch(url, body) { | |
return this.client.patch(url, body); | |
} | |
post(url, body, config) { | |
return this.client.post(url, body, config); | |
} | |
delete(url) { | |
return this.client.delete(url); | |
} | |
} | |
export default new Request(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment