mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-26 23:52:06 +00:00
32 lines
809 B
TypeScript
32 lines
809 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) {
|
|
// _ctx.response._data = new myBusinessResponse(_ctx.response._data)
|
|
},
|
|
|
|
onResponseError (_ctx) {
|
|
// throw new myBusinessError()
|
|
}
|
|
}
|
|
|
|
// for nice deep defaults, please use unjs/defu
|
|
const params = defu(options, defaults)
|
|
|
|
return useFetch(url, params)
|
|
}
|