Updated fetch to actually retry on 401 with new token

This commit is contained in:
lucast committed 2026-02-24 19:27:14 +01:00
1 parent 581c522b00
commit 464bbaef9e
3 files changed
+14 -15

No files matched your search

+10 -11
View File
@@ -4,7 +4,7 @@ import defu from "defu"
export function useApiFetch<DataT = any, ErrorT = any>(
url: string | Request | Ref<string | Request> | (() => string | Request),
options?: UseFetchOptions<DataT, ErrorT>,
authorize: boolean = true
authorize: boolean = true,
): ReturnType<typeof useFetch<DataT, ErrorT>> {
const baseUrl = import.meta.env.VITE_PUBLIC_BACKEND
@@ -15,26 +15,25 @@ export function useApiFetch<DataT = any, ErrorT = any>(
const defaults: UseFetchOptions<DataT, ErrorT> = {
baseURL: baseUrl,
retry: 1,
retryDelay: 0,
retryStatusCodes: [401],
headers:
authorize && sessionToken.value
? { Authorization: `Bearer ${sessionToken.value}` }
: {},
onResponseError: async ({ response, options }) => {
onResponseError: async ({ request, response, options }) => {
if (response.status == 401 && authorize) {
const newToken = await refreshSessionToken()
if (!newToken) return
const newOptions = {
...options,
headers: {
...(options.headers || {}),
Authorization: `Bearer ${newToken}`,
},
}
options.headers = {
...(options.headers as unknown as Record<string, string>),
// @ts-ignore
return await $fetch<DataT, ErrorT>(url, newOptions)
Authorization: `Bearer ${newToken}`,
}
}
},
}
+1 -1
View File
@@ -12,7 +12,7 @@ const { playAlbum, playShuffledAlbum, playAlbumAtIndex } = usePlayer()
</script>
<template>
<section class="info">
<section class="info" v-if="albumData">
<NuxtImg
:src="GET_FILE(albumData.file)"
width="300"
+3 -3
View File
@@ -62,13 +62,13 @@ export const cfetch = async (
let response
try {
response = await axios(url, config)
} catch {
if (response?.status == 401) {
} catch (error: any) {
if (error.response?.status == 401) {
if (!config.headers) config.headers = {}
config.headers.Authorization = `Bearer ${await refreshSessionToken()}`
response = await axios(url, config)
}
} else throw error
}
if (!response) throw new Error("Something went wrong. Please try again")