-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
useCustomFetch.ts
35 lines (27 loc) · 939 Bytes
/
useCustomFetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type { UseFetchOptions } from 'nuxt/app'
export async 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,
onRequest({ options }) {
options.headers = options.headers ?? new Headers()
// set user token if connected
if (userAuth.value) {
options.headers['Authorization'] = `Bearer ${userAuth.value}`
}
},
onResponse({ response }) {
// return new myBusinessResponse(response._data)ß
},
onResponseError({ error }) {
// add you error logic here
// return new myBusinessError(error)
},
}
// for nice deep defaults, please unjs/defu
const params = Object.assign(defaults, options)
return await useFetch(url, params)
}