| Numéro du ticket | Titre du ticket | |------------------|-----------------| | #203 | Réceptions — Parcours de pesée multi-étapes | ## Description de la PR [#203] Réceptions — Parcours de pesée multi-étapes ## Modification du .env ## Check list - [x] Pas de régression - [x] TU/TI/TF rédigée - [x] TU/TI/TF OK - [x] CHANGELOG modifié Reviewed-on: #3 Reviewed-by: THOLOT DECHENE Matthieu <matthieu@yuno.malio.fr> Co-authored-by: AUTIN Tristan <tristan@yuno.malio.fr> Co-committed-by: AUTIN Tristan <tristan@yuno.malio.fr>
56 lines
2.1 KiB
TypeScript
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, retry: 0 })
|
|
|
|
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 })
|
|
}
|
|
}
|
|
}
|