| 1 |
import { useMemo } from 'react' |
| 2 |
import axios from 'axios' |
| 3 |
import type { AxiosInstance, AxiosResponse, CreateAxiosDefaults } from 'axios' |
| 4 |
|
| 5 |
export interface AxiosAPI { |
| 6 |
get: <T>(url: string) => Promise<AxiosResponse<T, never>> |
| 7 |
post: <T, D>(url: string, data?: D) => Promise<AxiosResponse<T, D>> |
| 8 |
del: <T>(url: string) => Promise<AxiosResponse<T, never>> |
| 9 |
axiosInstance: AxiosInstance |
| 10 |
} |
| 11 |
|
| 12 |
const debugRequest = async <T, D = never>( |
| 13 |
method: 'GET' | 'POST' | 'PUT' | 'DELETE', |
| 14 |
url: string, |
| 15 |
doRequest: Promise<AxiosResponse<T, D>>, |
| 16 |
data?: D |
| 17 |
): Promise<AxiosResponse<T, D>> => { |
| 18 |
console.debug(`${method} ${url}`, ...data ? [data] : []) |
| 19 |
const response = await doRequest |
| 20 |
console.debug('Response', response) |
| 21 |
return response |
| 22 |
} |
| 23 |
|
| 24 |
export const useAxios = (defaultConfig: CreateAxiosDefaults): AxiosAPI => { |
| 25 |
const axiosInstance = useMemo(() => axios.create(defaultConfig), [defaultConfig]) |
| 26 |
|
| 27 |
return useMemo((): AxiosAPI => ({ |
| 28 |
get: <T>(url: string): Promise<AxiosResponse<T, never>> => |
| 29 |
debugRequest('GET', url, axiosInstance.get<T, AxiosResponse<T, never>, never>(url)), |
| 30 |
|
| 31 |
post: <T, D>(url: string, data?: D) => |
| 32 |
debugRequest('POST', url, axiosInstance.post<T, AxiosResponse<T, D>, D>(url, data), data), |
| 33 |
|
| 34 |
del: <T>(url: string) => |
| 35 |
debugRequest('DELETE', url, axiosInstance.delete<T, AxiosResponse<T, never>, never>(url)), |
| 36 |
|
| 37 |
axiosInstance |
| 38 |
}), [axiosInstance]) |
| 39 |
} |
| 40 |
|