Skip to content

Instantly share code, notes, and snippets.

@zuramai
Created January 20, 2023 11:31
Show Gist options
  • Save zuramai/784dd7c14ca6c4090ba6f00c93bb0a29 to your computer and use it in GitHub Desktop.
Save zuramai/784dd7c14ca6c4090ba6f00c93bb0a29 to your computer and use it in GitHub Desktop.
useFetch Wrapper
import type { NitroFetchRequest } from 'nitropack'
import type { KeyOfRes } from 'nuxt/dist/app/composables/asyncData'
import type { UseFetchOptions } from '#app'
type FetchOptions<T> = UseFetchOptions<
T extends void ? unknown : T,
(res: T extends void ? unknown : T) => T extends void ? unknown : T,
KeyOfRes<(res: T extends void ? unknown : T) => T extends void ? unknown : T>>
| undefined
export function useMyFetch<T>(
request: NitroFetchRequest,
opts?: FetchOptions<T>,
) {
const router = useRouter()
const config = useRuntimeConfig()
const token = useCookie<string>('token')
const options: FetchOptions<T> = {
...opts,
baseURL: config.public.baseURL,
onResponseError: ({ response }) => {
if (response.status === 401)
router.push('/auth/login')
},
}
if (token.value) {
options.headers = {
'Authorization': `Bearer ${token.value}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
return useFetch<T>(request, options)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment