useAxios.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { service } from '@/config/axios'
  2. import { config } from '@/config/axios/config'
  3. const { default_headers } = config
  4. const request = (option: AxiosConfig) => {
  5. const { url, method, params, data, headersType, responseType } = option
  6. return service({
  7. url: url,
  8. method,
  9. params,
  10. data,
  11. responseType: responseType,
  12. headers: {
  13. 'Content-Type': headersType || default_headers
  14. }
  15. })
  16. }
  17. async function getFn<T = any>(option: AxiosConfig): Promise<T> {
  18. const res = await request({ method: 'GET', ...option })
  19. return res.data
  20. }
  21. async function postFn<T = any>(option: AxiosConfig): Promise<T> {
  22. const res = await request({ method: 'POST', ...option })
  23. return res.data
  24. }
  25. async function deleteFn<T = any>(option: AxiosConfig): Promise<T> {
  26. const res = await request({ method: 'DELETE', ...option })
  27. return res.data
  28. }
  29. async function putFn<T = any>(option: AxiosConfig): Promise<T> {
  30. const res = await request({ method: 'PUT', ...option })
  31. return res.data
  32. }
  33. async function downloadFn<T = any>(option: AxiosConfig): Promise<T> {
  34. const res = await request({ method: 'GET', responseType: 'blob', ...option })
  35. return res as unknown as Promise<T>
  36. }
  37. async function uploadFn<T = any>(option: AxiosConfig): Promise<T> {
  38. option.headersType = 'multipart/form-data'
  39. const res = await request({ method: 'PUT', ...option })
  40. return res as unknown as Promise<T>
  41. }
  42. export const useAxios = () => {
  43. return {
  44. get: getFn,
  45. post: postFn,
  46. delete: deleteFn,
  47. put: putFn,
  48. download: downloadFn,
  49. upload: uploadFn
  50. }
  51. }