// plugins/api.ts import { useAuthStore } from '~/stores/auth' export default defineNuxtPlugin((nuxtApp) => { const auth = useAuthStore() // Función personalizada para hacer requests const apiFetch = async (url: string, options: any = {}) => { try { const res = await $fetch(url, { baseURL: useRuntimeConfig().public.apiBase, credentials: 'include', // para enviar cookies si es necesario headers: { ...(options.headers || {}), ...(auth.access ? { Authorization: `Bearer ${auth.access}` } : {}), }, ...options, }) return res } catch (error: any) { // Si no es 401, relanzamos el error if (error?.status !== 401) throw error // Si es el endpoint de refresh, cerramos sesión if (url.includes('refresh')) { auth.logout() return navigateTo('/login') } // Usuario inactivo if (error?.data?.code === 'user_inactive') { auth.logout() return navigateTo('/login') } // Intentar refresh try { await auth.refresh() return await apiFetch(url, options) // reintentar la petición original } catch { return navigateTo({ name: 'index', query: { redirected: 'true' } }) } } } // Inyectar como $api nuxtApp.provide('api', apiFetch) })