Nuxt/examples/other/use-custom-fetch-composable/composables/useCustomFetch.ts
2023-04-26 12:28:19 +01:00

32 lines
797 B
TypeScript

import type { UseFetchOptions } from 'nuxt/app'
import { defu } from 'defu'
export function useCustomFetch<T> (url: string, options: UseFetchOptions<T> = {}) {
const userAuth = useCookie('token')
const config = useRuntimeConfig()
const defaults: UseFetchOptions<T> = {
baseURL: config.baseUrl ?? 'https://api.nuxtjs.dev',
// cache request
key: url,
// set user token if connected
headers: userAuth.value
? { Authorization: `Bearer ${userAuth.value}` }
: {},
onResponse (__ctx) {
// return new myBusinessResponse(response._data)
},
onResponseError (__ctx) {
// return new myBusinessError(error)
}
}
// for nice deep defaults, please use unjs/defu
const params = defu(defaults, options)
return useFetch(url, params)
}