fetch.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. type fetchMethod =
  2. | "GET"
  3. | "HEAD"
  4. | "PATCH"
  5. | "POST"
  6. | "PUT"
  7. | "DELETE"
  8. | "CONNECT"
  9. | "OPTIONS"
  10. | "TRACE"
  11. | "get"
  12. | "head"
  13. | "patch"
  14. | "post"
  15. | "put"
  16. | "delete"
  17. | "connect"
  18. | "options"
  19. | "trace";
  20. const _fetch = <T>(
  21. url: string,
  22. options?: {
  23. method?: fetchMethod;
  24. body?: BodyInit;
  25. }
  26. ) => {
  27. const isLoading = useState<boolean>("isLoading");
  28. isLoading.value = true;
  29. return $fetch<T>(`${useRuntimeConfig().public.apiUrl}${url}`, {
  30. headers: {
  31. "Content-Type": "application/json",
  32. Authorization: `Bearer ${useCookie("token").value}`,
  33. },
  34. method: options?.method,
  35. body: options?.body,
  36. })
  37. .then((r) => {
  38. const resp = r as ApiResp<T>;
  39. if (resp.code !== 0) {
  40. const toadMsg = useState<string>("toadMsg");
  41. toadMsg.value = resp.msg;
  42. return;
  43. }
  44. return Promise.resolve(resp.data);
  45. })
  46. .finally(() => {
  47. isLoading.value = false;
  48. });
  49. };
  50. export const $get = <T>(url: string) => _fetch<T>(url);
  51. export const $post = <T>(url: string, body?: any) =>
  52. _fetch<T>(url, { method: "POST", body: JSON.stringify(body) });
  53. export const $put = <T>(url: string, body?: any) =>
  54. _fetch<T>(url, { method: "PUT", body: JSON.stringify(body) });
  55. export const $patch = <T>(url: string, body?: any) =>
  56. _fetch<T>(url, { method: "PATCH", body: JSON.stringify(body) });
  57. export const $delete = <T>(url: string) => _fetch<T>(url, { method: "DELETE" });