useApi.ts 1.8 KB
import { defu } from 'defu'
import type { UseFetchOptions } from 'nuxt/app'

export const useApi: typeof useFetch = <T>(url: MaybeRefOrGetter<string>, options: UseFetchOptions<T> = {}) => {
  const config = useRuntimeConfig()
  const accessToken = useCookie('accessToken')

  const defaults: UseFetchOptions<T> = {
    baseURL: config.public.apiBaseUrl,
    key: toValue(url),
    headers: accessToken.value ? { Authorization: `Bearer ${accessToken.value}` } : {},
  }

  // for nice deep defaults, please use unjs/defu
  const params = defu(options, defaults)

  return useFetch(url, params)
}

// import { defu } from 'defu'
// import { destr } from 'destr'
// import type { UseFetchOptions } from 'nuxt/app'

// export const useApi = <T>(url: MaybeRefOrGetter<string>, options: UseFetchOptions<T> = {}) => {
//   const config = useRuntimeConfig()
//   const accessToken = useCookie('accessToken')

//   const defaults: UseFetchOptions<T> = {
//     baseURL: config.public.apiBaseUrl || '/api',
//     key: toValue(url),
//     headers: {
//       Accept: 'application/json',
//       ...(accessToken.value ? { Authorization: `Bearer ${accessToken.value}` } : {}),
//     },
//     onResponse({ response }) {
//       // Parse response with destr (like Vite version)
//       try {
//         response._data = destr(response._data)
//       }
//       catch (error) {
//         console.error('Failed to parse response:', error)
//       }
//     },
//     onRequest({ options }) {
//       // Similar to `beforeFetch`
//       if (accessToken.value) {
//         options.headers = {
//           ...options.headers,
//           Authorization: `Bearer ${accessToken.value}`,
//         }
//       }
//     },
//   }

//   // Merge user options with defaults
//   const params = defu(options, defaults)

//   return useFetch<T>(url, params)
// }