Important Fixes, New mechanics, and many more
Some checks failed
CI / validate (push) Failing after 9m21s
Some checks failed
CI / validate (push) Failing after 9m21s
This commit is contained in:
33
apps/web/composables/useDngApi.ts
Normal file
33
apps/web/composables/useDngApi.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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 }
|
||||
}
|
||||
Reference in New Issue
Block a user