Skip to content

Commit

Permalink
chore: update useCustomFetch from atinux version (#71)
Browse files Browse the repository at this point in the history
* chore: update useCustomFetch from atinux version

* docs: add useCustomFetch read-more article
  • Loading branch information
maximepvrt authored Mar 12, 2024
1 parent a77e403 commit bbe3468
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 34 deletions.
2 changes: 2 additions & 0 deletions .docs/4.advanced/use-custom-fetch-composable.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ title: 'Use Custom Fetch Composable'
description: 'This example shows a convenient wrapper for the useFetch composable from nuxt. It allows you to customize the fetch request with default values and user authentication token.'
---

:read-more{to="https://notes.atinux.com/nuxt-custom-fetch" target="_blank"}

:sandbox{repo="nuxt/examples" branch="main" dir="examples/advanced/use-custom-fetch-composable" file="composables/useCustomFetch.ts"}
Original file line number Diff line number Diff line change
@@ -1,34 +1,11 @@
import type { UseFetchOptions } from '#app'
import { defu } from 'defu'

export function useCustomFetch<T> (url: string | (() => string), options: UseFetchOptions<T> = {}) {
const userAuth = useCookie('token')
const config = useRuntimeConfig()

const defaults: UseFetchOptions<T> = {
baseURL: config.baseUrl ?? 'https://api.nuxt.com',
// this overrides the default key generation, which includes a hash of
// url, method, headers, etc. - this should be used with care as the key
// is how Nuxt decides how responses should be deduplicated between
// client and server
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)
}
import type { UseFetchOptions } from 'nuxt/app';

export function useCustomFetch<T>(
url: string | (() => string),
options: UseFetchOptions<T> = {}
) {
return useFetch(url, {
...options,
$fetch: useNuxtApp().$customFetch,
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export default defineNuxtPlugin(() => {
const userAuth = useCookie('token')
const config = useRuntimeConfig()

const $customFetch = $fetch.create({
baseURL: config.baseUrl ?? 'https://api.nuxt.com',
onRequest({ request, options, error }) {
if (userAuth.value) {
// Add Authorization header
options.headers = options.headers || {}
options.headers.Authorization = `Bearer ${userAuth.value}`
}
},
onResponse ({ response }) {
// response._data = new myBusinessResponse(response._data)
},
onResponseError({ response }) {
if (response.status === 401) {
return navigateTo('/login')
}
}
})
// Expose to useNuxtApp().$customFetch
return {
provide: {
customFetch: $customFetch
}
}
})

0 comments on commit bbe3468

Please sign in to comment.