wip migration

This commit is contained in:
María
2025-08-14 15:12:29 +02:00
commit 61d96ac328
148 changed files with 31438 additions and 0 deletions

48
plugins/api.ts Normal file
View File

@@ -0,0 +1,48 @@
// 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)
})