diff --git a/frontend/composables/useApi.ts b/frontend/composables/useApi.ts index 94f57ec..ec296b4 100644 --- a/frontend/composables/useApi.ts +++ b/frontend/composables/useApi.ts @@ -21,6 +21,7 @@ export type ApiClient = { export type ApiFetchOptions = FetchOptions & { toast?: boolean + toastOn401?: boolean toastTitle?: string toastErrorMessage?: string toastSuccessMessage?: string @@ -102,9 +103,31 @@ export const useApi = (): ApiClient => { } }, async onResponseError({ response, error, options }) { + const apiOptions = options as ApiFetchOptions<'json'> if (response?.status === 401) { const requestUrl = typeof options?.url === 'string' ? options.url : '' - if (!requestUrl.includes('/login_check') && !requestUrl.includes('/logout')) { + 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() @@ -115,10 +138,10 @@ export const useApi = (): ApiClient => { isHandlingUnauthorized = false } } + return } - const apiOptions = options as ApiFetchOptions<'json'> if (apiOptions?.toast === false) { return } diff --git a/frontend/services/auth.ts b/frontend/services/auth.ts index 7076822..bef14f5 100644 --- a/frontend/services/auth.ts +++ b/frontend/services/auth.ts @@ -8,6 +8,7 @@ export const getCurrentUser = () => { export const login = (username: string, password: string) => { const api = useApi() return api.post('/login_check', { username, password }, { + toastOn401: true, toastErrorKey: 'errors.auth.login' }) }