index.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { ElMessage } from 'element-plus'
  2. type UrlType = string | Request | Ref<string | Request> | (() => string | Request)
  3. export interface RequestOptions {
  4. method?: any
  5. params?: any
  6. }
  7. const request = async (url: UrlType, params: any, options: RequestOptions) => {
  8. const headers = useRequestHeaders(['cookie'])
  9. const { apiBase: baseURL } = useRuntimeConfig().public
  10. const { method = ((options?.method || 'GET') as string).toUpperCase() } = options
  11. return await useFetch(url as string, {
  12. default: () => [],
  13. baseURL,
  14. method,
  15. params: { ...params }, //temp hook
  16. headers,
  17. // lazy: true,
  18. credentials: 'include',
  19. body: method === 'POST' ? JSON.stringify(params) : undefined,
  20. onRequest({ request, options }) {
  21. // Set the request headers
  22. // options.headers = options.headers || {};
  23. },
  24. onRequestError({ request, options, error }) {
  25. ElMessage.closeAll()
  26. error && ElMessage.error('Sorry, The Data Request Failed')
  27. // Handle the request errors
  28. },
  29. onResponse({ request, response, options }) {
  30. // Process the response data
  31. return response._data
  32. },
  33. onResponseError({ request, response, options }) {
  34. console.log('🚀 ~ file: MyRequest.ts:42 ~ onResponseError ~ request:', request)
  35. // Handle the response errors
  36. },
  37. })
  38. }
  39. export const useDefaultRequest = {
  40. get: (url: UrlType, params?: any, option?: RequestOptions) => {
  41. return request(url, params, { method: 'GET', ...option })
  42. },
  43. post: (url: UrlType, params?: any, option?: RequestOptions) => {
  44. return request(url, params, { method: 'POST', ...option })
  45. },
  46. }