| 1 |
import axios from "axios"; |
| 2 |
import { AxiosRequestConfig } from "axios"; |
| 3 |
import { camelToSnakeObj, snakeToCamelObj } from "@/utils/services"; |
| 4 |
import { asyncCall } from "@/utils/helpers"; |
| 5 |
|
| 6 |
const TIMEOUT_TIME = 120_000; |
| 7 |
|
| 8 |
export const axiosInstance = axios.create({ |
| 9 |
timeout: TIMEOUT_TIME, |
| 10 |
withCredentials: false, |
| 11 |
headers: { |
| 12 |
Accept: "application/json;charset=UTF-8", |
| 13 |
"Content-Type": "application/json;charset=UTF-8", |
| 14 |
}, |
| 15 |
}); |
| 16 |
|
| 17 |
// REQUEST INTERCEPTOR - camel to snake |
| 18 |
axiosInstance.interceptors.request.use((req: any) => { |
| 19 |
if (req.plain) return req; |
| 20 |
|
| 21 |
if (req.data) { |
| 22 |
req.data = camelToSnakeObj(req.data); |
| 23 |
} |
| 24 |
|
| 25 |
if (req.params) { |
| 26 |
req.params = camelToSnakeObj(req.params); |
| 27 |
} |
| 28 |
|
| 29 |
return req; |
| 30 |
}); |
| 31 |
|
| 32 |
axiosInstance.interceptors.response.use( |
| 33 |
(res: any) => { |
| 34 |
return snakeToCamelObj({ |
| 35 |
...res, |
| 36 |
data: res.data, |
| 37 |
}); |
| 38 |
}, |
| 39 |
(error: Error) => Promise.reject(error) |
| 40 |
); |
| 41 |
|
| 42 |
const httpService = { |
| 43 |
get<T>(url: string, config?: AxiosRequestConfig) { |
| 44 |
return asyncCall<T>(axiosInstance.get(url, config)); |
| 45 |
}, |
| 46 |
post<T>(url: string, data?: any, config?: AxiosRequestConfig) { |
| 47 |
return asyncCall<T>(axiosInstance.post(url, data, config)); |
| 48 |
}, |
| 49 |
put<T>(url: string, data?: any, config?: AxiosRequestConfig) { |
| 50 |
return asyncCall<T>(axiosInstance.put(url, data, config)); |
| 51 |
}, |
| 52 |
patch<T>(url: string, data?: any, config?: AxiosRequestConfig) { |
| 53 |
return asyncCall<T>(axiosInstance.patch(url, data, config)); |
| 54 |
}, |
| 55 |
delete<T>(url: string, config?: AxiosRequestConfig) { |
| 56 |
return asyncCall<T>(axiosInstance.delete(url, config)); |
| 57 |
}, |
| 58 |
request<T>(config: AxiosRequestConfig) { |
| 59 |
return asyncCall<T>(axiosInstance(config)); |
| 60 |
}, |
| 61 |
}; |
| 62 |
|
| 63 |
export default httpService; |
| 64 |
|