import { useRuntimeConfig } from "nuxt/app"; import type { ApiCallOptions, RequestBody } from "~/types/api"; export const useApi = () => { const config = useRuntimeConfig(); const apiBase = config.public.baseUrl; const defaultHeaders = { Accept: "application/json", "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest", }; const apiCall = async ( endpoint: string, options: ApiCallOptions = {} ): Promise => { options.retryCount = options.retryCount || 0; try { const headers: Record = { ...defaultHeaders, ...options.headers, }; return await $fetch(endpoint, { baseURL: apiBase, method: options.method || "GET", headers, body: options.body, }); } catch (error) { if (options.retryCount < 3) { options.retryCount++; return await apiCall(endpoint, options); } console.error("Erro na API:", error); throw error; } }; const get = (endpoint: string, headers?: Record) => apiCall(endpoint, { method: "GET", headers }); const post = ( endpoint: string, body?: RequestBody, headers?: Record ) => apiCall(endpoint, { method: "POST", body, headers }); const put = ( endpoint: string, body?: RequestBody, headers?: Record ) => apiCall(endpoint, { method: "PUT", body, headers }); const del = (endpoint: string, headers?: Record) => apiCall(endpoint, { method: "DELETE", headers }); const patch = ( endpoint: string, body?: RequestBody, headers?: Record ) => apiCall(endpoint, { method: "PATCH", body, headers }); return { get, post, put, delete: del, patch }; };