#fetch refresh token interceptor - doesn't return successfully retried request

3 messages · Page 1 of 1 (latest)

glad drum
#

I have a page with a fetch call like:

const products = ref([])

onMounted(async () => {
    const response = await useFetchApi(url, {
        credentials: 'include'
    }).then((response) => {
        products.value = response.data.value
    })
})
#

I have created a custom fetch composable useFetchApi. When the above API call returns a 401 unauthorized status code, the custom fetch composable fetches a new access token and retries the request with it, which is sucessful. However, the response in the above mounted call is the 401 response, not the successful retried response. How can I fix that?

#
import { UseFetchOptions } from 'nuxt/dist/app/composables'
import { useAuthStore } from '@/stores/auth'

export const useFetchApi = async (url: string, options?: UseFetchOptions<object>) => {

    const authStore = useAuthStore()
    const { clearAuth, refreshToken } = authStore

    let isRefreshing = false
    let failedQueue: Promise<any>[] = []

    const processQueue = (error = null) => {
        failedQueue.forEach(({resolve, reject}) => {
            if (error) {
                reject(error)
            } else {
                resolve()
            }
        })

        failedQueue = []
    }

    return await useFetch(url, {
        ...options,
        async onRequest({ request, options }) {
            console.log("[fetch request]")

            // const headers = new Headers(options.headers)
            // headers.set("Authorization", "Bearer Token")

            // options.headers = headers
        },
        async onRequestError({ request, options, error }) {
            console.log("[fetch request error]")
        },
        async onResponse({ request, response, options }) {
            console.log("[fetch response]")
            console.log(response)
            return response._data
        },
        async onResponseError({ request, response, options }) {
            console.log("[fetch response error]")
            console.log(request, response, options)

            const originalRequest = options

            return new Promise(function (resolve, reject) {
                refreshToken(true)
                    .then(response => {
                        processQueue()
                        return resolve(useFetchApi(request, originalRequest))
                    })
            })
        },
    });
};