feat : Ajout d'un layout default.vue + Ajout de la couleur primary dans la conf tailwind.config.ts +Ajout d'un composable pour gérer les appels API (GET, POST)
This commit is contained in:
42
frontend/composables/useApi.ts
Normal file
42
frontend/composables/useApi.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user