58589e93d0
Auto Tag Develop / tag (push) Successful in 6s
Lien Lesstime : #50 ## Résumé Refacto : extraction de la logique fetch/CRUD inline de la page categories (ERP-49) vers deux composables dédiés, conformément au pattern Starseed (useSidebar / useModules). - **useCategoriesAdmin** : singleton state (`categories` + `types` + `loading` + `error`). Pré-chargement des types au mount de la page (au lieu d'un fetch par ouverture du drawer). Reset au logout via `onAuthSessionCleared` + appel explicite dans `logout.vue`. - **useCategoryForm** : state local par form (pas singleton, contrairement à `useCategoriesAdmin`). Valide côté client en miroir des RG back (RG-1.02 / RG-1.04 / RG-1.05), mappe les erreurs 409 (RG-1.07 doublon) et 422 (violations API Platform) sur les bons champs. `submitCreate` / `submitUpdate` / `submitDelete` renvoient la ressource ou `null` pour découpler la décision de fermeture du drawer. La page et le drawer deviennent purement présentationnels — aucune régression UX attendue (mêmes validations, mêmes toasts, même bascule view → edit via `isDirty` exposé par le composable). ## Décisions - `useCategoriesAdmin` porte aussi les types (`fetchTypes`), pas seulement `categories` — sinon le drawer continuerait à fetcher tout seul et la refacto n'aurait rien centralisé. - `buildCreatePayload` retourne `Record<string, unknown>` (pas `CategoryCreateInput`) car la signature `useApi.post(body: AnyObject)` n'accepte pas les types stricts (variance TS). - Reset au logout : double mécanisme conservé (auto via `onAuthSessionCleared` pour 401, explicite dans `logout.vue` pour logout volontaire — pattern existant Starseed). ## Tests - `npx nuxi typecheck` ✓ 0 erreur nouvelle (1 erreur pré-existante sur `modules/catalog/nuxt.config.ts` héritée d'ERP-49) - `make nuxt-test` ✓ 43/43, 0 régression - PHPUnit ✓ 311/311 (pre-commit) - Manuel navigateur : à valider (cahier de test consigné dans Lesstime #50) ## ⚠ Note d'intégration La branche contient encore les 3 commits ERP-49 (`4046910`, `216f388`, `934a12b`) car elle a été créée depuis la branche ERP-49 avant son merge sur develop. Selon l'ordre de merge : soit ERP-49 est mergée d'abord (cette MR ne contiendra plus que le commit ERP-50 après rebase auto), soit cette MR embarque tout l'historique catalog. Reviewed-on: #25 Co-authored-by: tristan <tristan@yuno.malio.fr> Co-committed-by: tristan <tristan@yuno.malio.fr>
188 lines
6.8 KiB
TypeScript
188 lines
6.8 KiB
TypeScript
import type { FetchOptions , FetchError } from 'ofetch'
|
|
import { $fetch } from 'ofetch'
|
|
import { extractApiErrorMessage } from '~/shared/utils/api'
|
|
|
|
export type AnyObject = Record<string, unknown>
|
|
|
|
export type ApiClient = {
|
|
get<T>(url: string, query?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
|
|
post<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
|
|
put<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
|
|
patch<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
|
|
delete<T>(url: string, query?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
|
|
}
|
|
|
|
export type ApiFetchOptions<ResponseType extends 'json' | 'blob'> =
|
|
FetchOptions<ResponseType> & {
|
|
toast?: boolean
|
|
toastOn401?: boolean
|
|
toastTitle?: string
|
|
toastErrorMessage?: string
|
|
toastSuccessMessage?: string
|
|
toastErrorKey?: string
|
|
toastSuccessKey?: string
|
|
}
|
|
|
|
let isHandlingUnauthorized = false
|
|
|
|
export function useApi(): ApiClient {
|
|
const config = useRuntimeConfig()
|
|
const baseURL = config.public.apiBase || '/api'
|
|
const toast = useToast()
|
|
const auth = useAuthStore()
|
|
const nuxtApp = useNuxtApp()
|
|
const i18n = nuxtApp.$i18n as
|
|
| {
|
|
t: (key: string) => string
|
|
te?: (key: string) => boolean
|
|
}
|
|
| undefined
|
|
const t = (key: string) => (i18n?.t ? String(i18n.t(key)) : key)
|
|
const te = (key: string) => (i18n?.te ? i18n.te(key) : false)
|
|
|
|
function extractErrorMessage(error: unknown, responseData?: unknown): string {
|
|
const data = responseData ?? (error as FetchError)?.data
|
|
const msg = extractApiErrorMessage(data)
|
|
if (msg) return msg
|
|
return (error as FetchError)?.message ?? 'Erreur inconnue.'
|
|
}
|
|
|
|
const methodErrorKeys: Record<string, string> = {
|
|
GET: 'errors.http.get',
|
|
POST: 'errors.http.post',
|
|
PUT: 'errors.http.put',
|
|
PATCH: 'errors.http.patch',
|
|
DELETE: 'errors.http.delete'
|
|
}
|
|
|
|
const client = $fetch.create({
|
|
baseURL,
|
|
retry: 0,
|
|
credentials: 'include',
|
|
onResponse({ options, response }) {
|
|
const apiOptions = options as ApiFetchOptions<'json'>
|
|
if (apiOptions?.toast === false) {
|
|
return
|
|
}
|
|
|
|
if (response?.status && response.status >= 400) {
|
|
return
|
|
}
|
|
|
|
const successKey = apiOptions?.toastSuccessKey
|
|
const successMessage =
|
|
apiOptions?.toastSuccessMessage ||
|
|
(successKey ? (te(successKey) ? t(successKey) : successKey) : '')
|
|
|
|
if (successMessage) {
|
|
toast.success({
|
|
title: 'Succes',
|
|
message: successMessage
|
|
})
|
|
}
|
|
},
|
|
async onResponseError({ response, error, options }) {
|
|
const apiOptions = options as ApiFetchOptions<'json'>
|
|
if (response?.status === 401) {
|
|
const requestUrl = typeof options?.url === 'string' ? options.url : ''
|
|
const isLoginCheck = requestUrl.includes('/login_check')
|
|
const isLogout = requestUrl.includes('/logout')
|
|
const shouldToast401 = apiOptions?.toastOn401 === true && apiOptions?.toast !== false
|
|
|
|
if (shouldToast401) {
|
|
const errorKey = apiOptions?.toastErrorKey
|
|
const errorMessage =
|
|
errorKey ? (te(errorKey) ? t(errorKey) : errorKey) : ''
|
|
const extractedMessage = extractErrorMessage(error, response?._data)
|
|
const message =
|
|
apiOptions?.toastErrorMessage ||
|
|
errorMessage ||
|
|
extractedMessage ||
|
|
'Une erreur est survenue.'
|
|
|
|
toast.error({
|
|
title: apiOptions?.toastTitle ?? 'Erreur',
|
|
message
|
|
})
|
|
}
|
|
|
|
if (!isLoginCheck && !isLogout) {
|
|
if (!isHandlingUnauthorized) {
|
|
isHandlingUnauthorized = true
|
|
auth.clearSession()
|
|
await navigateTo('/login')
|
|
isHandlingUnauthorized = false
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
if (apiOptions?.toast === false) {
|
|
return
|
|
}
|
|
|
|
const method =
|
|
typeof options?.method === 'string' ? options.method.toUpperCase() : 'GET'
|
|
const defaultKey = methodErrorKeys[method]
|
|
const defaultMessage =
|
|
defaultKey && te(defaultKey) ? t(defaultKey) : ''
|
|
const errorKey = apiOptions?.toastErrorKey
|
|
const errorMessage =
|
|
errorKey ? (te(errorKey) ? t(errorKey) : errorKey) : ''
|
|
const extractedMessage = extractErrorMessage(error, response?._data)
|
|
const message =
|
|
apiOptions?.toastErrorMessage ||
|
|
errorMessage ||
|
|
defaultMessage ||
|
|
extractedMessage ||
|
|
'Une erreur est survenue.'
|
|
|
|
toast.error({
|
|
title: apiOptions?.toastTitle ?? 'Erreur',
|
|
message
|
|
})
|
|
}
|
|
})
|
|
|
|
function request<T>(
|
|
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
|
url: string,
|
|
options: ApiFetchOptions<'json'> = {}
|
|
) {
|
|
const needsJsonBody = method === 'POST' || method === 'PUT'
|
|
const needsMergePatch = method === 'PATCH'
|
|
const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData
|
|
|
|
const headers = new Headers(options.headers as HeadersInit | undefined)
|
|
|
|
if (!isFormData) {
|
|
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: ApiFetchOptions<'json'> = {}) {
|
|
return request<T>('GET', url, { ...options, query })
|
|
},
|
|
post<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
|
|
return request<T>('POST', url, { ...options, body })
|
|
},
|
|
put<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
|
|
return request<T>('PUT', url, { ...options, body })
|
|
},
|
|
patch<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
|
|
return request<T>('PATCH', url, { ...options, body })
|
|
},
|
|
delete<T>(url: string, query: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
|
|
return request<T>('DELETE', url, { ...options, query })
|
|
}
|
|
}
|
|
}
|