Files
FEDEO/frontend/plugins/api.ts

93 lines
3.1 KiB
TypeScript

export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const toast = useToast()
const api = $fetch.create({
baseURL: config.public.apiBase,
credentials: "include",
async onRequest({ options }) {
const token = useCookie<string | null>("token", { path: "/" }).value
// Falls im Request explizit ein anderer JWT übergeben wird
if (options.context?.jwt) {
options.headers = {
...options.headers,
Authorization: `Bearer ${options.context.jwt}`,
}
} else if (token) {
options.headers = {
...options.headers,
Authorization: `Bearer ${token}`,
}
}
},
async onRequestError({error}) {
toast.add({
title: "Fehler",
description: "Eine Anfrage konnte nicht ausgeführt werden.",
color: 'red',
icon: 'i-heroicons-exclamation-triangle-20-solid',
timeout: 5000 // Bleibt 5 Sekunden sichtbar
})
},
async onResponseError({ response, request }) {
// Toasts nur im Client anzeigen
console.log(response)
if (!process.client) return
const status = response.status
const requestPath = String(request)
let title = "Fehler"
let description = "Ein unerwarteter Fehler ist aufgetreten."
switch (status) {
case 400:
title = "Anfrage fehlerhaft"
description = "Die Daten konnten nicht korrekt verarbeitet werden."
break
case 401:
title = "Nicht angemeldet"
description = "Deine Sitzung ist abgelaufen oder ungültig."
if (!requestPath.includes("/auth/login")) {
const auth = useAuthStore()
if (!auth.loading && auth.user) {
auth.expireSession()
}
}
break
case 403:
title = "Zugriff verweigert"
description = "Du hast keine Berechtigung für diesen Bereich."
break
case 404:
title = "Nicht gefunden"
description = "Die gesuchte Ressource wurde nicht gefunden."
break
case 500:
title = "Server-Fehler"
description = "Internes Problem. Bitte versuche es später erneut."
break
}
// Nuxt UI Toast Notification
toast.add({
title: title,
description: description,
color: 'red',
icon: 'i-heroicons-exclamation-triangle-20-solid',
timeout: 5000 // Bleibt 5 Sekunden sichtbar
})
}
})
return {
provide: {
api
}
}
})