httpService.ts
63 lines
| 1 | import type { AxiosRequestConfig } from 'axios'; |
| 2 | import axios from 'axios'; |
| 3 | |
| 4 | import { camelToSnakeObj, snakeToCamelObj } from '@/utils/caseConversion'; |
| 5 | import { asyncCall } from '@/utils/helpers'; |
| 6 | |
| 7 | const TIMEOUT_TIME = 120_000; |
| 8 | |
| 9 | export const axiosInstance = axios.create({ |
| 10 | timeout: TIMEOUT_TIME, |
| 11 | withCredentials: true, |
| 12 | headers: { |
| 13 | Accept: 'application/json;charset=UTF-8', |
| 14 | 'Content-Type': 'application/json;charset=UTF-8' |
| 15 | } |
| 16 | }); |
| 17 | |
| 18 | axiosInstance.interceptors.request.use((req) => { |
| 19 | if ((req as unknown as { plain?: boolean }).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) => |
| 34 | snakeToCamelObj({ |
| 35 | ...res, |
| 36 | data: res.data |
| 37 | }), |
| 38 | (error: Error) => Promise.reject(error) |
| 39 | ); |
| 40 | |
| 41 | const httpService = { |
| 42 | get<T>(url: string, config?: AxiosRequestConfig) { |
| 43 | return asyncCall<T>(axiosInstance.get(url, config)); |
| 44 | }, |
| 45 | post<T>(url: string, data?: unknown, config?: AxiosRequestConfig) { |
| 46 | return asyncCall<T>(axiosInstance.post(url, data, config)); |
| 47 | }, |
| 48 | put<T>(url: string, data?: unknown, config?: AxiosRequestConfig) { |
| 49 | return asyncCall<T>(axiosInstance.put(url, data, config)); |
| 50 | }, |
| 51 | patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig) { |
| 52 | return asyncCall<T>(axiosInstance.patch(url, data, config)); |
| 53 | }, |
| 54 | delete<T>(url: string, config?: AxiosRequestConfig) { |
| 55 | return asyncCall<T>(axiosInstance.delete(url, config)); |
| 56 | }, |
| 57 | request<T>(config: AxiosRequestConfig) { |
| 58 | return asyncCall<T>(axiosInstance(config)); |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | export default httpService; |
| 63 |