diff --git a/frontend/composables/useApi.ts b/frontend/composables/useApi.ts index a9abd61..186e395 100644 --- a/frontend/composables/useApi.ts +++ b/frontend/composables/useApi.ts @@ -1,9 +1,14 @@ import type { FetchOptions } from 'ofetch' import { $fetch, FetchError } from 'ofetch' +export type AnyObject = Record + export type ApiClient = { - get(path: string, options?: FetchOptions<'json'>): Promise - post(path: string, body?: unknown, options?: FetchOptions<'json'>): Promise + get(url: string, query?: AnyObject, options?: FetchOptions<'json'>): Promise + post(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise + put(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise + patch(url: string, body?: AnyObject, options?: FetchOptions<'json'>): Promise + delete(url: string, query?: AnyObject, options?: FetchOptions<'json'>): Promise } export const useApi = (): ApiClient => { @@ -11,32 +16,29 @@ export const useApi = (): ApiClient => { const baseURL = config.public.apiBase ?? '/api' const client = $fetch.create({ baseURL }) + const request = ( + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', + url: string, + options: FetchOptions<'json'> = {} + ) => { + return client(url, { ...options, method }) + } + return { - get(path: string, options?: FetchOptions<'json'>) { - return client(path, { ...options, method: 'GET' }) + get(url: string, query: AnyObject = {}, options: FetchOptions<'json'> = {}) { + return request('GET', url, { ...options, query }) }, - post(path: string, body?: unknown, options?: FetchOptions<'json'>) { - return client(path, { ...options, method: 'POST', body }) + post(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) { + return request('POST', url, { ...options, body }) + }, + put(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) { + return request('PUT', url, { ...options, body }) + }, + patch(url: string, body: AnyObject = {}, options: FetchOptions<'json'> = {}) { + return request('PATCH', url, { ...options, body }) + }, + delete(url: string, query: AnyObject = {}, options: FetchOptions<'json'> = {}) { + return request('DELETE', url, { ...options, query }) } } } - -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 -}