34 lines
1.0 KiB
TypeScript
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 }
|
|
}
|