import type { FetchOptions } from 'ofetch' import { useStorage } from '@vueuse/core' type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' interface HttpRequestOptions extends FetchOptions { data?: T } export const useHttpService = () => { const config = useRuntimeConfig() const token = useStorage('id_token', 'GuestAccess') /** * Constructs the full API URL */ const getFullUrl = (endpoint: string): string => { return `${config.public.NUXT_PUBLIC_BASE_URL}${config.public.NUXT_PUBLIC_API_NAME}${endpoint}` } /** * Base fetch method with common configuration */ const baseFetch = async ( method: HttpMethod, url: string, options: HttpRequestOptions = {} ) => { const headers = { ...options.headers, ...(token.value ? { Authorization: token.value } : {}) } try { const response = await $fetch(getFullUrl(url), { method, headers, ...options, body: options.data || options.body }) return response } catch (error) { // Handle errors globally or rethrow for specific handling console.error(`HTTP ${method} error for ${url}:`, error) throw error } } return { /** * GET request */ getRequest: (url: string, options?: HttpRequestOptions) => baseFetch('GET', url, options), /** * POST request */ postRequest: (url: string, data?: any, options?: HttpRequestOptions) => baseFetch('POST', url, { ...options, data }), /** * PUT request */ putRequest: (url: string, data?: any, options?: HttpRequestOptions) => baseFetch('PUT', url, { ...options, data }), /** * PATCH request */ patchRequest: (url: string, data?: any, options?: HttpRequestOptions) => baseFetch('PATCH', url, { ...options, data }), /** * DELETE request */ deleteRequest: (url: string, options?: HttpRequestOptions) => baseFetch('DELETE', url, options) } }