43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import type { FetchOptions } from 'ofetch'
|
|
import { $fetch, FetchError } from 'ofetch'
|
|
|
|
export type ApiClient = {
|
|
get<T>(path: string, options?: FetchOptions<'json'>): Promise<T>
|
|
post<T>(path: string, body?: unknown, options?: FetchOptions<'json'>): Promise<T>
|
|
}
|
|
|
|
export const useApi = (): ApiClient => {
|
|
const config = useRuntimeConfig()
|
|
const baseURL = config.public.apiBase ?? '/api'
|
|
const client = $fetch.create({ baseURL })
|
|
|
|
return {
|
|
get<T>(path: string, options?: FetchOptions<'json'>) {
|
|
return client<T>(path, { ...options, method: 'GET' })
|
|
},
|
|
post<T>(path: string, body?: unknown, options?: FetchOptions<'json'>) {
|
|
return client<T>(path, { ...options, method: 'POST', body })
|
|
}
|
|
}
|
|
}
|
|
|
|
export const getApiStatus = (error: unknown): number | null => {
|
|
if (error && typeof error === 'object') {
|
|
if (error instanceof FetchError) {
|
|
return error.status ?? error.response?.status ?? null
|
|
}
|
|
|
|
const maybeResponse = (error as { response?: { status?: number } }).response
|
|
if (typeof maybeResponse?.status === 'number') {
|
|
return maybeResponse.status
|
|
}
|
|
|
|
const maybeStatus = (error as { status?: number }).status
|
|
if (typeof maybeStatus === 'number') {
|
|
return maybeStatus
|
|
}
|
|
}
|
|
|
|
return null
|
|
}
|