useApi.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { useRuntimeConfig } from "nuxt/app";
  2. import type { ApiCallOptions, RequestBody } from "~/types/api";
  3. export const useApi = () => {
  4. const config = useRuntimeConfig();
  5. const apiBase = config.public.baseUrl;
  6. const defaultHeaders = {
  7. Accept: "application/json",
  8. "Content-Type": "application/json",
  9. "X-Requested-With": "XMLHttpRequest",
  10. };
  11. const apiCall = async <T>(
  12. endpoint: string,
  13. options: ApiCallOptions = {}
  14. ): Promise<T> => {
  15. options.retryCount = options.retryCount || 0;
  16. try {
  17. const headers: Record<string, string> = {
  18. ...defaultHeaders,
  19. ...options.headers,
  20. };
  21. return await $fetch<T>(endpoint, {
  22. baseURL: apiBase,
  23. method: options.method || "GET",
  24. headers,
  25. body: options.body,
  26. });
  27. } catch (error) {
  28. if (options.retryCount < 3) {
  29. options.retryCount++;
  30. return await apiCall<T>(endpoint, options);
  31. }
  32. console.error("Erro na API:", error);
  33. throw error;
  34. }
  35. };
  36. const get = <T>(endpoint: string, headers?: Record<string, string>) =>
  37. apiCall<T>(endpoint, { method: "GET", headers });
  38. const post = <T>(
  39. endpoint: string,
  40. body?: RequestBody,
  41. headers?: Record<string, string>
  42. ) => apiCall<T>(endpoint, { method: "POST", body, headers });
  43. const put = <T>(
  44. endpoint: string,
  45. body?: RequestBody,
  46. headers?: Record<string, string>
  47. ) => apiCall<T>(endpoint, { method: "PUT", body, headers });
  48. const del = <T>(endpoint: string, headers?: Record<string, string>) =>
  49. apiCall<T>(endpoint, { method: "DELETE", headers });
  50. const patch = <T>(
  51. endpoint: string,
  52. body?: RequestBody,
  53. headers?: Record<string, string>
  54. ) => apiCall<T>(endpoint, { method: "PATCH", body, headers });
  55. return { get, post, put, delete: del, patch };
  56. };