-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Expand file tree
/
Copy pathapi.ts
More file actions
32 lines (29 loc) · 1.08 KB
/
Copy pathapi.ts
File metadata and controls
32 lines (29 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import type { NitroFetchOptions, NitroFetchRequest } from 'nitropack'
import { getAuthToken, removeAuthToken } from '@/utils/auth-token'
type APIOptions = Omit<NitroFetchOptions<NitroFetchRequest>, 'headers'> & {
headers?: Record<string, string>
}
export function useAPI<T = unknown>(api: string, options?: APIOptions): Promise<T>
export async function useAPI(api: string, options?: APIOptions): Promise<unknown> {
const { headers, ...fetchOptions } = options ?? {}
const requestOptions: NitroFetchOptions<NitroFetchRequest> = {
...fetchOptions,
credentials: 'same-origin',
headers: {
'Authorization': `Bearer ${getAuthToken() ?? ''}`,
'X-Requested-With': 'XMLHttpRequest',
...headers,
},
}
try {
return await $fetch(api, requestOptions)
}
catch (error: unknown) {
if (typeof error === 'object' && error !== null && 'status' in error && error.status === 401) {
removeAuthToken()
if (import.meta.client && window.location.pathname !== '/dashboard/login')
window.location.assign('/dashboard/login')
}
throw error
}
}