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