Created
January 20, 2023 11:31
-
-
Save zuramai/784dd7c14ca6c4090ba6f00c93bb0a29 to your computer and use it in GitHub Desktop.
useFetch Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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