Files
Dungeons-Ground/apps/web/composables/useDngApi.ts
pavel444-byte 438e5af0ad
Some checks failed
CI / validate (push) Failing after 9m21s
Important Fixes, New mechanics, and many more
2026-08-15 17:37:57 +05:00

34 lines
1.0 KiB
TypeScript

interface DngApiOptions {
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
body?: Record<string, unknown>
query?: Record<string, string | number | boolean | undefined>
}
export function useDngApi() {
const auth = useDngAuth()
async function api<T>(path: string, options: DngApiOptions = {}): Promise<T> {
const token = await auth.accessToken()
try {
const response = await $fetch(path, {
...options,
headers: { Authorization: `Bearer ${token}` },
} as Parameters<typeof $fetch>[1])
return response as T
} catch (cause) {
const error = cause as { statusCode?: number; status?: number; response?: { status?: number } }
const status = error.statusCode ?? error.status ?? error.response?.status
if (status === 401) {
auth.invalidate()
if (import.meta.client) {
localStorage.setItem('dng-post-auth-redirect', window.location.pathname + window.location.search)
await navigateTo('/')
}
}
throw cause
}
}
return { api }
}