nuxt-start/composables/useApi.ts
2026-01-02 10:29:43 +01:00

44 lines
1.0 KiB
TypeScript

/**
* Központi API composable
* Az összes API hívás ezen keresztül történik
*/
export const useApi = () => {
const config = useRuntimeConfig()
const baseUrl = config.public.apiBase as string
/**
* API végpont URL összeállítása
*/
const getUrl = (endpoint: string): string => {
// Ha már teljes URL, visszaadjuk
if (endpoint.startsWith('http')) {
return endpoint
}
// Biztosítjuk, hogy az endpoint /-vel kezdődjön
const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`
return `${baseUrl}${path}`
}
/**
* useFetch wrapper az API hívásokhoz
*/
const apiFetch = <T>(endpoint: string, options?: Parameters<typeof useFetch>[1]) => {
return useFetch<T>(getUrl(endpoint), options)
}
/**
* $fetch wrapper az API hívásokhoz (nem reaktív, közvetlen hívás)
*/
const apiRequest = <T>(endpoint: string, options?: Parameters<typeof $fetch>[1]) => {
return $fetch<T>(getUrl(endpoint), options)
}
return {
baseUrl,
getUrl,
apiFetch,
apiRequest
}
}