useAxios.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. console.info(res)
  20. return res.data
  21. }
  22. async function postFn<T = any>(option: AxiosConfig): Promise<T> {
  23. const res = await request({ method: 'POST', ...option })
  24. console.info(res)
  25. return res.data
  26. }
  27. async function deleteFn<T = any>(option: AxiosConfig): Promise<T> {
  28. const res = await request({ method: 'DELETE', ...option })
  29. console.info(res)
  30. return res.data
  31. }
  32. async function putFn<T = any>(option: AxiosConfig): Promise<T> {
  33. const res = await request({ method: 'PUT', ...option })
  34. console.info(res)
  35. return res.data
  36. }
  37. async function downloadFn<T = any>(option: AxiosConfig): Promise<T> {
  38. const res = await request({ method: 'GET', responseType: 'blob', ...option })
  39. console.info(res)
  40. return res as unknown as Promise<T>
  41. }
  42. async function uploadFn<T = any>(option: AxiosConfig): Promise<T> {
  43. option.headersType = 'multipart/form-data'
  44. const res = await request({ method: 'PUT', ...option })
  45. console.info(res)
  46. return res as unknown as Promise<T>
  47. }
  48. export const useAxios = () => {
  49. return {
  50. get: getFn,
  51. post: postFn,
  52. delete: deleteFn,
  53. put: putFn,
  54. download: downloadFn,
  55. upload: uploadFn
  56. }
  57. }