Files
Ferme/frontend/composables/useApi.ts

56 lines
2.1 KiB
TypeScript

import type { FetchOptions } from 'ofetch'
import { $fetch, FetchError } from 'ofetch'
export type AnyObject = Record<string, unknown>
export type ApiClient = {
get<T>(url: string, query?: AnyObject, options?: FetchOptions<'json'>): Promise<T>
post<T>(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise<T>
put<T>(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise<T>
patch<T>(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise<T>
delete<T>(url: string, query?: AnyObject, options?: FetchOptions<'json'>): Promise<T>
}
export const useApi = (): ApiClient => {
const config = useRuntimeConfig()
const baseURL = config.public.apiBase ?? '/api'
const client = $fetch.create({ baseURL })
const request = <T>(
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
url: string,
options: FetchOptions<'json'> = {}
) => {
const needsJsonBody = method === 'POST' || method === 'PUT'
const needsMergePatch = method === 'PATCH'
const headers = new Headers(options.headers as HeadersInit | undefined)
if (needsMergePatch && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/merge-patch+json')
} else if (needsJsonBody && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
return client<T>(url, { ...options, method, headers })
}
return {
get<T>(url: string, query: AnyObject = {}, options: FetchOptions<'json'> = {}) {
return request<T>('GET', url, { ...options, query })
},
post<T>(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) {
return request<T>('POST', url, { ...options, body })
},
put<T>(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) {
return request<T>('PUT', url, { ...options, body })
},
patch<T>(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) {
return request<T>('PATCH', url, { ...options, body })
},
delete<T>(url: string, query: AnyObject = {}, options: FetchOptions<'json'> = {}) {
return request<T>('DELETE', url, { ...options, query })
}
}
}