Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion frontend/src/components/cards/CardIListtem.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Card } from '@/client/types.gen'
import { stripHtml } from '@/utils/text'
import { stripHtml } from '@/utils/textUtils'
import { Box, HStack, IconButton, Text } from '@chakra-ui/react'
import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/commonUI/GuestModeNotice.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useAuthContext } from '@/hooks/useAuthContext'
import { useAuthContext } from '@/contexts/useAuthContext'
import { HStack, Text } from '@chakra-ui/react'
import { useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/commonUI/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Logo from '@/assets/Logo.svg'
import { useAuthContext } from '@/hooks/useAuthContext'
import { useAuthContext } from '@/contexts/useAuthContext'
import { Flex, IconButton, Image } from '@chakra-ui/react'
import { Link } from '@tanstack/react-router'
import { useState } from 'react'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/commonUI/TextCounter.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MAX_CHARACTERS, WARNING_THRESHOLD } from '@/utils/text'
import { MAX_CHARACTERS, WARNING_THRESHOLD } from '@/utils/textUtils'
import { Text } from '@chakra-ui/react'

interface TextCounterProps {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/stats/StatsSummaryGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Box, SimpleGrid, Text } from '@chakra-ui/react'
import { useTranslation } from 'react-i18next'

import type { CollectionBasicInfo, PracticeSessionStats } from '@/client'
import { calculateAverageAccuracy, calculateLearningTrend } from '@/utils/stats'
import { calculateAverageAccuracy, calculateLearningTrend } from '@/utils/statsUtils'

interface StatCardProps {
label: string
Expand Down
64 changes: 27 additions & 37 deletions frontend/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useAuthContext } from '@/contexts/useAuthContext'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useAuthContext } from './useAuthContext'

import type { ApiRequestOptions } from '@/client/core/ApiRequestOptions'
import { toaster } from '@/components/ui/toaster'
import { AxiosError } from 'axios'
import { type ErrorResponse, handleError, mapToApiError } from '@/utils/errorsUtils'
import type { AxiosError } from 'axios'
import {
type Body_login_login_access_token as AccessToken,
LoginService,
Expand All @@ -14,13 +16,6 @@ import {
UsersService,
} from '../client'

interface ErrorResponse {
body: {
detail?: string
}
status?: number
}

const useAuth = () => {
const { t } = useTranslation()
const [error, setError] = useState<string | null>(null)
Expand All @@ -45,22 +40,19 @@ const useAuth = () => {
})
},
onError: (err: Error | AxiosError | ErrorResponse) => {
const errDetail =
err instanceof AxiosError
? err.message
: 'body' in err && typeof err.body === 'object' && err.body
? String(err.body.detail) || t('general.errors.somethingWentWrong')
: t('general.errors.somethingWentWrong')
toaster.create({
title: t('general.errors.errorCreatingAccount'),
description: errDetail,
type: 'error',
const request: ApiRequestOptions = {
method: 'POST',
url: '/signup',
}
const apiErrorDto = mapToApiError(err, request)
const message = handleError(apiErrorDto, {
toastTitle: t('general.errors.errorCreatingAccount'),
})
const status = (err as AxiosError).status ?? (err as ErrorResponse).status
if (status === 409) {

if (apiErrorDto.status === 409) {
setError(t('general.errors.emailAlreadyInUse') || t('general.errors.somethingWentWrong'))
} else {
setError(errDetail)
setError(message)
}
},
onSettled: () => {
Expand All @@ -81,22 +73,20 @@ const useAuth = () => {
navigate({ to: '/collections' })
},
onError: (err: Error | AxiosError | ErrorResponse) => {
const errDetail =
err instanceof AxiosError
? err.message
: 'body' in err && typeof err.body === 'object' && err.body
? String(err.body.detail) || t('general.errors.somethingWentWrong')
: t('general.errors.somethingWentWrong')

const finalError = Array.isArray(errDetail)
? t('general.errors.invalidCredentials')
: errDetail

toaster.create({
title: t('general.errors.loginFailed'),
description: finalError,
type: 'error',
const request: ApiRequestOptions = {
method: 'POST',
url: '/login',
}
const apiErrorDto = mapToApiError(err, request)
const message = handleError(apiErrorDto, {
toastTitle: t('general.errors.loginFailed'),
fallbackMessage: t('general.errors.somethingWentWrong'),
})

let finalError = message
if (apiErrorDto.status === 401) {
finalError = t('general.errors.invalidCredentials')
}
setError(finalError)
},
})
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/hooks/useTextCounter.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { toaster } from '@/components/ui/toaster'
import { MAX_CHARACTERS } from '@/utils/text'
import { MAX_CHARACTERS } from '@/utils/textUtils'
import type { Editor } from '@tiptap/react'
import { useCallback, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import './i18n'
import { ColorModeProvider } from '@/components/ui/color-mode'
import { AuthProvider } from '@/contexts/useAuthContext'
import { ChakraProvider } from '@chakra-ui/react'
import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import { ApiError, OpenAPI } from './client'
import AnalyticsConsent from './components/commonUI/AnalyticsConsent'
import { AuthProvider } from './hooks/useAuthContext'
import { routeTree } from './routeTree.gen'
import { system } from './theme'

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/routes/_publicLayout/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BlueButton, DefaultButton } from '@/components/commonUI/Button'
import { Footer } from '@/components/commonUI/Footer'
import { useColorMode } from '@/components/ui/color-mode'
import { useAuthContext } from '@/hooks/useAuthContext'
import { useAuthContext } from '@/contexts/useAuthContext'
import { Container, Heading, Image, Stack, Text, VStack } from '@chakra-ui/react'
import { Link, createFileRoute, useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/routes/_publicLayout/login.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import Logo from '@/assets/Logo.svg'
import useAuth from '@/hooks/useAuth'
import { emailPattern } from '@/utils/patternsUtils'
import { Container, Field, Fieldset, Image, Text } from '@chakra-ui/react'
import { Link, createFileRoute, redirect } from '@tanstack/react-router'
import { type SubmitHandler, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import type { Body_login_login_access_token as AccessToken } from '../../client'
import { DefaultButton } from '../../components/commonUI/Button'
import { DefaultInput } from '../../components/commonUI/Input'
import { emailPattern } from '../../utils'

export const Route = createFileRoute('/_publicLayout/login')({
component: Login,
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/routes/_publicLayout/signup.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import Logo from '@/assets/Logo.svg'
import useAuth from '@/hooks/useAuth'
import { emailPattern } from '@/utils/patternsUtils'
import { confirmPasswordRules, passwordRules } from '@/utils/rulesUtils'
import { Button, Container, Field, Fieldset, Image, Text } from '@chakra-ui/react'
import { Link, createFileRoute, redirect } from '@tanstack/react-router'
import { type SubmitHandler, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import type { UserRegister } from '../../client'
import { DefaultInput } from '../../components/commonUI/Input'
import PasswordInput from '../../components/commonUI/PasswordInput'
import { confirmPasswordRules, emailPattern, passwordRules } from '../../utils'

export const Route = createFileRoute('/_publicLayout/signup')({
component: SignUp,
Expand Down
73 changes: 0 additions & 73 deletions frontend/src/utils.ts

This file was deleted.

94 changes: 94 additions & 0 deletions frontend/src/utils/errorsUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { ApiError } from '@/client'
import type { ApiRequestOptions } from '@/client/core/ApiRequestOptions'
import type { ApiResult } from '@/client/core/ApiResult'
import { toaster } from '@/components/ui/toaster'
import { translate } from '@/utils/translationUtils'
import type { AxiosError } from 'axios'

type ToastType = 'error' | 'success' | 'info' | 'warning'

export const handleError = (
err: ApiError,
options?: {
toastTitle?: string
toastType?: ToastType
fallbackMessage?: string
silent?: boolean
},
): string => {
const errDetail = (err.body as { detail?: string | { msg: string }[] })?.detail
let errorMessage = options?.fallbackMessage || translate('general.errors.default')

if (typeof errDetail === 'string') {
errorMessage = errDetail
} else if (Array.isArray(errDetail) && errDetail.length > 0) {
errorMessage = errDetail[0].msg
}

if (!options?.silent) {
toaster.create({
title: options?.toastTitle || translate('general.errors.error'),
description: errorMessage,
type: options?.toastType || 'error',
})
}

return errorMessage
}

export interface ErrorResponse {
body: {
detail?: string
}
status?: number
}

export function mapToApiError(
err: Error | AxiosError | ErrorResponse,
request: ApiRequestOptions,
): ApiError {
let url = ''
let status = 0
let statusText = ''
let body: unknown = {}
let message = 'Unexpected error'

switch (true) {
case 'isAxiosError' in err && (err as AxiosError).isAxiosError: {
const axiosErr = err as AxiosError
url = axiosErr.config?.url ?? ''
status = axiosErr.response?.status ?? 404
statusText = axiosErr.response?.statusText ?? ''
body = axiosErr.response?.data ?? {}
message = axiosErr.message
break
}
case 'body' in err: {
const errorResponse = err as ErrorResponse
url = request.url
status = errorResponse.status ?? 404
statusText = ''
body = errorResponse.body
message = errorResponse.body?.detail ?? 'Unknown error'
break
}
default: {
url = request.url
status = 404
statusText = ''
body = {}
message = err.message
break
}
}

const response: ApiResult = {
url,
status,
statusText,
body,
ok: status === 200,
}

return new ApiError(request, response, message)
}
11 changes: 11 additions & 0 deletions frontend/src/utils/patternsUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { translate } from '@/utils/translationUtils'

export const emailPattern = {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: translate('general.errors.invalidEmail'),
}

export const namePattern = {
value: /^[A-Za-z\s\u00C0-\u017F]{1,30}$/,
message: translate('general.errors.invalidName'),
}
Loading