59 lines
1.7 KiB
TypeScript
59 lines
1.7 KiB
TypeScript
export function useApi() {
|
|
const config = useRuntimeConfig()
|
|
const { token, logout } = useAuth()
|
|
|
|
async function apiFetch<T>(url: string, options: any = {}) {
|
|
try {
|
|
return await $fetch<T>(url, {
|
|
baseURL: config.public.apiBase,
|
|
headers: {
|
|
...(options.headers || {}),
|
|
...(token.value ? { Authorization: `Bearer ${token.value}` } : {})
|
|
},
|
|
...options
|
|
})
|
|
} catch (error: any) {
|
|
// Netzwerkfehler oder Server nicht erreichbar
|
|
if (!error.response) {
|
|
console.error("API unreachable:", error)
|
|
throw new Error("Der Server ist nicht erreichbar.")
|
|
}
|
|
|
|
const status = error.response.status
|
|
const data = error.response._data
|
|
|
|
// 401 → Token ungültig oder abgelaufen
|
|
if (status === 401) {
|
|
console.warn("API returned 401 — logging out")
|
|
logout()
|
|
throw new Error("Deine Sitzung ist abgelaufen. Bitte erneut einloggen.")
|
|
}
|
|
|
|
// 403 → keine Berechtigung
|
|
if (status === 403) {
|
|
throw new Error("Du hast keine Berechtigung für diese Aktion.")
|
|
}
|
|
|
|
// 400 → Validierungsfehler
|
|
if (status === 400) {
|
|
throw new Error(data?.detail || "Ungültige Eingabe.")
|
|
}
|
|
|
|
// 404 → nicht gefunden
|
|
if (status === 404) {
|
|
throw new Error("Die angeforderte Ressource wurde nicht gefunden.")
|
|
}
|
|
|
|
// 500 → Serverfehler
|
|
if (status >= 500) {
|
|
console.error("Server error:", data)
|
|
throw new Error("Interner Serverfehler. Bitte später erneut versuchen.")
|
|
}
|
|
|
|
// Fallback
|
|
throw new Error(data?.detail || "Unbekannter Fehler.")
|
|
}
|
|
}
|
|
|
|
return { apiFetch }
|
|
}
|