feat(admin-ui): record CRUD with json-schema-driven form
POST/PUT/DELETE формы для записей справочников. Schema-driven рендер полей из definition.schemaJson — i18n-aware (x-localized → input на каждый supportedLocale), enum → select, type → text/number/checkbox/array. Валидация через ajv (Draft-07, match backend networknt validator). - new: api/mutations.ts с Idempotency-Key (crypto.randomUUID) и query invalidation - new: SchemaDrivenForm — react-hook-form + ajv compile per-schema, errors через setError по ajv instancePath - new: Modal (Esc + backdrop click) и confirm dialog для close-операции - nginx: regex location ^/api/v1/dictionaries/[^/]+$ → writer (admin schema fetch) - queries: dictionaryDetailQuery возвращает full def с schemaJson - i18n: RU/EN ключи для CRUD (create/edit/close, validFrom/validTo, confirm)
This commit is contained in:
@@ -15,6 +15,19 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# /api/v1/dictionaries/{name} (без /records) — admin endpoint, отдаёт schema_json.
|
||||
# Только writer его реализует. Regex-location имеет приоритет над префиксом ниже.
|
||||
location ~ ^/api/v1/dictionaries/[^/]+$ {
|
||||
set $backend "ordinis-app.${ORDINIS_NAMESPACE}.svc.${CLUSTER_DOMAIN}";
|
||||
proxy_pass http://$backend$request_uri;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_pass_request_headers on;
|
||||
}
|
||||
|
||||
# GET → read-api, мутирующие → writer.
|
||||
# FQDN в proxy_pass нужен потому что nginx resolver не использует search list.
|
||||
# Namespace и cluster-domain инжектятся через ENV (см. admin-ui Deployment).
|
||||
|
||||
@@ -9,13 +9,17 @@
|
||||
"preview": "vite preview --host 0.0.0.0 --port 4173"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@tanstack/react-router": "^1.86.0",
|
||||
"ajv": "^8.17.1",
|
||||
"ajv-formats": "^3.0.1",
|
||||
"axios": "^1.7.9",
|
||||
"i18next": "^24.0.5",
|
||||
"i18next-browser-languagedetector": "^8.0.2",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.54.2",
|
||||
"react-i18next": "^15.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+2211
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,5 @@
|
||||
import axios from 'axios'
|
||||
|
||||
/**
|
||||
* Centralized axios instance. JWT injection вешается через interceptor:
|
||||
* когда @nstart/auth интегрируется, добавляем Authorization: Bearer ...
|
||||
*/
|
||||
export const apiClient = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE ?? '/api/v1',
|
||||
timeout: 10_000,
|
||||
@@ -12,7 +8,6 @@ export const apiClient = axios.create({
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
const lang = (typeof navigator !== 'undefined' && navigator.language) || 'ru-RU'
|
||||
config.headers['Accept-Language'] = `${lang},ru-RU;q=0.9,en-US;q=0.8`
|
||||
// JWT placeholder
|
||||
const token = localStorage.getItem('ordinis.token')
|
||||
if (token) config.headers['Authorization'] = `Bearer ${token}`
|
||||
return config
|
||||
@@ -28,12 +23,14 @@ apiClient.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
export type DataScope = 'PUBLIC' | 'INTERNAL' | 'RESTRICTED'
|
||||
|
||||
export type DictionaryDefinition = {
|
||||
id: string
|
||||
name: string
|
||||
displayName?: string
|
||||
description?: string
|
||||
scope: 'PUBLIC' | 'INTERNAL' | 'RESTRICTED'
|
||||
scope: DataScope
|
||||
schemaVersion: string
|
||||
bundle: string
|
||||
supportedLocales: string[]
|
||||
@@ -42,12 +39,59 @@ export type DictionaryDefinition = {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type JsonSchema = {
|
||||
type?: string
|
||||
title?: string
|
||||
description?: string
|
||||
properties?: Record<string, JsonSchema>
|
||||
required?: string[]
|
||||
enum?: unknown[]
|
||||
format?: string
|
||||
pattern?: string
|
||||
minLength?: number
|
||||
maxLength?: number
|
||||
minimum?: number
|
||||
maximum?: number
|
||||
items?: JsonSchema
|
||||
additionalProperties?: boolean | JsonSchema
|
||||
['x-localized']?: boolean
|
||||
default?: unknown
|
||||
}
|
||||
|
||||
export type DictionaryDetail = DictionaryDefinition & {
|
||||
schemaJson: JsonSchema
|
||||
}
|
||||
|
||||
export type FlattenedRecord = {
|
||||
id: string
|
||||
businessKey: string
|
||||
data: Record<string, unknown>
|
||||
dataScope: 'PUBLIC' | 'INTERNAL' | 'RESTRICTED'
|
||||
dataScope: DataScope
|
||||
validFrom: string
|
||||
validTo: string
|
||||
_meta?: { locale?: string }
|
||||
}
|
||||
|
||||
export type RecordResponse = {
|
||||
id: string
|
||||
dictionaryId: string
|
||||
businessKey: string
|
||||
data: Record<string, unknown>
|
||||
geometryWkt?: string
|
||||
dataScope: DataScope
|
||||
validFrom: string
|
||||
validTo: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
createdBy?: string
|
||||
updatedBy?: string
|
||||
version: number
|
||||
}
|
||||
|
||||
export type CreateRecordRequest = {
|
||||
businessKey: string
|
||||
data: Record<string, unknown>
|
||||
geometryWkt?: string
|
||||
validFrom?: string
|
||||
validTo?: string
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
apiClient,
|
||||
type CreateRecordRequest,
|
||||
type RecordResponse,
|
||||
} from './client'
|
||||
|
||||
const idempotencyKey = () =>
|
||||
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
|
||||
export const useCreateRecord = (dictionaryName: string) => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (req: CreateRecordRequest): Promise<RecordResponse> => {
|
||||
const { data } = await apiClient.post<RecordResponse>(
|
||||
`/dictionaries/${dictionaryName}/records`,
|
||||
req,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey() } },
|
||||
)
|
||||
return data
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['records', dictionaryName] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useUpdateRecord = (dictionaryName: string) => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (params: {
|
||||
businessKey: string
|
||||
payload: CreateRecordRequest
|
||||
}): Promise<RecordResponse> => {
|
||||
const { data } = await apiClient.put<RecordResponse>(
|
||||
`/dictionaries/${dictionaryName}/records/${encodeURIComponent(params.businessKey)}`,
|
||||
params.payload,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey() } },
|
||||
)
|
||||
return data
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['records', dictionaryName] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useCloseRecord = (dictionaryName: string) => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (params: { businessKey: string; reason?: string }): Promise<void> => {
|
||||
await apiClient.delete(
|
||||
`/dictionaries/${dictionaryName}/records/${encodeURIComponent(params.businessKey)}`,
|
||||
{ params: params.reason ? { reason: params.reason } : undefined },
|
||||
)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['records', dictionaryName] })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,17 +1,31 @@
|
||||
import { useQuery, queryOptions } from '@tanstack/react-query'
|
||||
import { apiClient, type DictionaryDefinition, type FlattenedRecord } from './client'
|
||||
import {
|
||||
apiClient,
|
||||
type DictionaryDefinition,
|
||||
type DictionaryDetail,
|
||||
type FlattenedRecord,
|
||||
} from './client'
|
||||
|
||||
export const dictionariesQuery = queryOptions({
|
||||
queryKey: ['dictionaries'],
|
||||
queryKey: ['dictionaries'] as const,
|
||||
queryFn: async (): Promise<DictionaryDefinition[]> => {
|
||||
const { data } = await apiClient.get<DictionaryDefinition[]>('/dictionaries')
|
||||
return data
|
||||
},
|
||||
})
|
||||
|
||||
export const dictionaryDetailQuery = (name: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['dictionary', name] as const,
|
||||
queryFn: async (): Promise<DictionaryDetail> => {
|
||||
const { data } = await apiClient.get<DictionaryDetail>(`/dictionaries/${name}`)
|
||||
return data
|
||||
},
|
||||
})
|
||||
|
||||
export const recordsQuery = (dictionaryName: string, scopeCsv: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['records', dictionaryName, scopeCsv],
|
||||
queryKey: ['records', dictionaryName, scopeCsv] as const,
|
||||
queryFn: async (): Promise<FlattenedRecord[]> => {
|
||||
const { data } = await apiClient.get<FlattenedRecord[]>(
|
||||
`/${dictionaryName}/records`,
|
||||
@@ -22,5 +36,6 @@ export const recordsQuery = (dictionaryName: string, scopeCsv: string) =>
|
||||
})
|
||||
|
||||
export const useDictionaries = () => useQuery(dictionariesQuery)
|
||||
export const useDictionaryDetail = (name: string) => useQuery(dictionaryDetailQuery(name))
|
||||
export const useRecords = (dictionaryName: string, scopeCsv: string) =>
|
||||
useQuery(recordsQuery(dictionaryName, scopeCsv))
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useForm, Controller, type SubmitHandler } from 'react-hook-form'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Ajv, { type ErrorObject } from 'ajv'
|
||||
import addFormats from 'ajv-formats'
|
||||
import type { CreateRecordRequest, JsonSchema } from '@/api/client'
|
||||
|
||||
type FormValues = {
|
||||
businessKey: string
|
||||
validFrom: string
|
||||
validTo: string
|
||||
data: Record<string, unknown>
|
||||
}
|
||||
|
||||
type Props = {
|
||||
schema: JsonSchema
|
||||
supportedLocales: string[]
|
||||
defaultLocale: string
|
||||
defaultValues?: Partial<FormValues>
|
||||
mode: 'create' | 'edit'
|
||||
isPending: boolean
|
||||
serverError?: string | null
|
||||
onSubmit: (req: CreateRecordRequest) => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
const ajv = new Ajv({ allErrors: true, strict: false })
|
||||
addFormats(ajv)
|
||||
|
||||
const isLocalized = (s: JsonSchema): boolean => Boolean(s['x-localized'])
|
||||
|
||||
const fieldLabel = (key: string, schema: JsonSchema): string =>
|
||||
schema.title ?? key
|
||||
|
||||
export const SchemaDrivenForm = ({
|
||||
schema,
|
||||
supportedLocales,
|
||||
defaultLocale,
|
||||
defaultValues,
|
||||
mode,
|
||||
isPending,
|
||||
serverError,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: Props) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const validator = useMemo(() => {
|
||||
try {
|
||||
return ajv.compile(schema)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}, [schema])
|
||||
|
||||
const properties = schema.properties ?? {}
|
||||
const required = new Set(schema.required ?? [])
|
||||
|
||||
const { register, handleSubmit, control, setError, formState } = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
businessKey: defaultValues?.businessKey ?? '',
|
||||
validFrom: defaultValues?.validFrom ?? '',
|
||||
validTo: defaultValues?.validTo ?? '',
|
||||
data: defaultValues?.data ?? {},
|
||||
},
|
||||
})
|
||||
|
||||
const submit: SubmitHandler<FormValues> = (values) => {
|
||||
if (validator) {
|
||||
const ok = validator(values.data)
|
||||
if (!ok && validator.errors) {
|
||||
applyAjvErrors(validator.errors, setError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const req: CreateRecordRequest = {
|
||||
businessKey: values.businessKey.trim(),
|
||||
data: values.data,
|
||||
validFrom: values.validFrom || undefined,
|
||||
validTo: values.validTo || undefined,
|
||||
}
|
||||
onSubmit(req)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(submit)} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{t('form.businessKey')} <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
disabled={mode === 'edit'}
|
||||
{...register('businessKey', { required: true, minLength: 1 })}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 disabled:bg-zinc-100 disabled:text-zinc-500 font-mono"
|
||||
placeholder="MY_RECORD_KEY"
|
||||
/>
|
||||
{formState.errors.businessKey && (
|
||||
<p className="text-xs text-red-600 mt-1">{t('form.error.required')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{t('form.validFrom')}
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
{...register('validFrom')}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{t('form.validTo')}
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
{...register('validTo')}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-zinc-200 pt-4">
|
||||
<h3 className="text-sm font-semibold text-zinc-700 mb-3">{t('form.dataFields')}</h3>
|
||||
<div className="space-y-3">
|
||||
{Object.entries(properties).map(([key, propSchema]) => (
|
||||
<FieldRenderer
|
||||
key={key}
|
||||
fieldKey={key}
|
||||
schema={propSchema}
|
||||
required={required.has(key)}
|
||||
control={control}
|
||||
supportedLocales={supportedLocales}
|
||||
defaultLocale={defaultLocale}
|
||||
fieldError={formState.errors.data?.[key as keyof FormValues['data']]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{serverError && (
|
||||
<div className="px-3 py-2 bg-red-50 border border-red-200 rounded text-sm text-red-700">
|
||||
{serverError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-zinc-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
disabled={isPending}
|
||||
className="px-4 py-2 text-sm border border-zinc-300 rounded hover:bg-zinc-50 disabled:opacity-50"
|
||||
>
|
||||
{t('form.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending}
|
||||
className="px-4 py-2 text-sm bg-brand-600 text-white rounded hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
{isPending ? t('form.saving') : t('form.save')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
type FieldRendererProps = {
|
||||
fieldKey: string
|
||||
schema: JsonSchema
|
||||
required: boolean
|
||||
control: ReturnType<typeof useForm<FormValues>>['control']
|
||||
supportedLocales: string[]
|
||||
defaultLocale: string
|
||||
fieldError?: unknown
|
||||
}
|
||||
|
||||
const FieldRenderer = ({
|
||||
fieldKey,
|
||||
schema,
|
||||
required,
|
||||
control,
|
||||
supportedLocales,
|
||||
defaultLocale,
|
||||
fieldError,
|
||||
}: FieldRendererProps) => {
|
||||
const label = fieldLabel(fieldKey, schema)
|
||||
const errorMsg = (fieldError as { message?: string } | undefined)?.message
|
||||
|
||||
if (isLocalized(schema)) {
|
||||
return (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{label}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
<span className="text-xs text-zinc-400 ml-1">(i18n)</span>
|
||||
</label>
|
||||
<div className="space-y-2 pl-3 border-l-2 border-zinc-200">
|
||||
{supportedLocales.map((loc) => (
|
||||
<Controller
|
||||
key={loc}
|
||||
control={control}
|
||||
name={`data.${fieldKey}.${loc}` as `data.${string}`}
|
||||
render={({ field }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-mono text-zinc-500 w-12">
|
||||
{loc === defaultLocale ? <strong>{loc}</strong> : loc}
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
{...field}
|
||||
value={(field.value as string | undefined) ?? ''}
|
||||
className="flex-1 px-3 py-1.5 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{schema.description && (
|
||||
<p className="text-xs text-zinc-500 mt-1">{schema.description}</p>
|
||||
)}
|
||||
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (schema.enum) {
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`data.${fieldKey}` as `data.${string}`}
|
||||
render={({ field }) => (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{label}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
</label>
|
||||
<select
|
||||
{...field}
|
||||
value={(field.value as string | undefined) ?? ''}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 bg-white"
|
||||
>
|
||||
<option value="">—</option>
|
||||
{schema.enum?.map((v) => (
|
||||
<option key={String(v)} value={String(v)}>
|
||||
{String(v)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (schema.type === 'boolean') {
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`data.${fieldKey}` as `data.${string}`}
|
||||
render={({ field }) => (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(field.value)}
|
||||
onChange={(e) => field.onChange(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</label>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (schema.type === 'integer' || schema.type === 'number') {
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`data.${fieldKey}` as `data.${string}`}
|
||||
render={({ field }) => (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{label}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step={schema.type === 'integer' ? 1 : 'any'}
|
||||
value={(field.value as number | undefined) ?? ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(e.target.value === '' ? undefined : Number(e.target.value))
|
||||
}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (schema.type === 'array' && schema.items?.type === 'string') {
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`data.${fieldKey}` as `data.${string}`}
|
||||
render={({ field }) => (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{label}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
<span className="text-xs text-zinc-400 ml-1">(comma-separated)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={Array.isArray(field.value) ? (field.value as string[]).join(', ') : ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(
|
||||
e.target.value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
)
|
||||
}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={`data.${fieldKey}` as `data.${string}`}
|
||||
render={({ field }) => {
|
||||
const isLong = (schema.maxLength ?? 0) > 200
|
||||
return (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{label}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
</label>
|
||||
{isLong ? (
|
||||
<textarea
|
||||
{...field}
|
||||
value={(field.value as string | undefined) ?? ''}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type={schema.format === 'date-time' ? 'datetime-local' : 'text'}
|
||||
{...field}
|
||||
value={(field.value as string | undefined) ?? ''}
|
||||
pattern={schema.pattern}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
/>
|
||||
)}
|
||||
{schema.description && (
|
||||
<p className="text-xs text-zinc-500 mt-1">{schema.description}</p>
|
||||
)}
|
||||
{errorMsg && <p className="text-xs text-red-600 mt-1">{errorMsg}</p>}
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const applyAjvErrors = (
|
||||
errors: ErrorObject[],
|
||||
setError: ReturnType<typeof useForm<FormValues>>['setError'],
|
||||
) => {
|
||||
for (const err of errors) {
|
||||
const path = err.instancePath.replace(/^\//, '').replace(/\//g, '.')
|
||||
const fieldPath = path ? (`data.${path}` as `data.${string}`) : 'data'
|
||||
setError(fieldPath as 'data', { type: 'ajv', message: err.message ?? 'invalid' })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
title: string
|
||||
onClose: () => void
|
||||
children: ReactNode
|
||||
widthClass?: string
|
||||
}
|
||||
|
||||
export const Modal = ({ open, title, onClose, children, widthClass = 'max-w-2xl' }: Props) => {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const handleKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', handleKey)
|
||||
return () => window.removeEventListener('keydown', handleKey)
|
||||
}, [open, onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-start justify-center bg-zinc-900/50 backdrop-blur-sm pt-16 px-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className={`bg-white rounded-lg shadow-xl w-full ${widthClass} max-h-[85vh] flex flex-col`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between px-5 py-3 border-b border-zinc-200">
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-zinc-400 hover:text-zinc-700 text-xl leading-none w-8 h-8 rounded hover:bg-zinc-100"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-y-auto p-5">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -20,7 +20,24 @@ i18n
|
||||
'dict.col.scope': 'Scope',
|
||||
'dict.col.validFrom': 'Действует с',
|
||||
'dict.col.locale': 'Локаль',
|
||||
'dict.col.actions': 'Действия',
|
||||
'dict.list.records': 'записей',
|
||||
'dict.action.create': 'Создать запись',
|
||||
'dict.action.edit': 'Изменить',
|
||||
'dict.action.close': 'Закрыть',
|
||||
'dict.confirmClose.title': 'Закрыть запись?',
|
||||
'dict.confirmClose.body':
|
||||
'Запись «{{key}}» будет помечена как закрытая (valid_to = now). Действие обратимо через создание новой версии.',
|
||||
'dict.confirmClose.reason': 'Причина (опционально)',
|
||||
'dict.confirmClose.reasonPlaceholder': 'например, «дубликат» или «выведено из эксплуатации»',
|
||||
'form.businessKey': 'Бизнес-ключ',
|
||||
'form.validFrom': 'Действует с',
|
||||
'form.validTo': 'Действует до',
|
||||
'form.dataFields': 'Поля записи',
|
||||
'form.cancel': 'Отмена',
|
||||
'form.save': 'Сохранить',
|
||||
'form.saving': 'Сохранение...',
|
||||
'form.error.required': 'Обязательное поле',
|
||||
'loading': 'Загрузка...',
|
||||
'error.failed': 'Не удалось загрузить данные',
|
||||
},
|
||||
@@ -35,7 +52,24 @@ i18n
|
||||
'dict.col.scope': 'Scope',
|
||||
'dict.col.validFrom': 'Valid from',
|
||||
'dict.col.locale': 'Locale',
|
||||
'dict.col.actions': 'Actions',
|
||||
'dict.list.records': 'records',
|
||||
'dict.action.create': 'Create record',
|
||||
'dict.action.edit': 'Edit',
|
||||
'dict.action.close': 'Close',
|
||||
'dict.confirmClose.title': 'Close record?',
|
||||
'dict.confirmClose.body':
|
||||
'Record "{{key}}" will be marked as closed (valid_to = now). Reversible by creating a new version.',
|
||||
'dict.confirmClose.reason': 'Reason (optional)',
|
||||
'dict.confirmClose.reasonPlaceholder': 'e.g., "duplicate" or "decommissioned"',
|
||||
'form.businessKey': 'Business key',
|
||||
'form.validFrom': 'Valid from',
|
||||
'form.validTo': 'Valid to',
|
||||
'form.dataFields': 'Record fields',
|
||||
'form.cancel': 'Cancel',
|
||||
'form.save': 'Save',
|
||||
'form.saving': 'Saving...',
|
||||
'form.error.required': 'Required field',
|
||||
'loading': 'Loading...',
|
||||
'error.failed': 'Failed to load data',
|
||||
},
|
||||
|
||||
@@ -1,15 +1,105 @@
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
// Файл регенерируется TanStackRouterVite plugin'ом во время `vite dev`/`vite build`.
|
||||
// Этот stub существует только для cold start — Vite plugin перепишет его перед
|
||||
// собственно сборкой.
|
||||
import { Route as RootRoute } from './routes/__root'
|
||||
import { Route as IndexRoute } from './routes/index'
|
||||
import { Route as DictionariesRoute } from './routes/dictionaries'
|
||||
import { Route as DictionariesNameRoute } from './routes/dictionaries.$name'
|
||||
|
||||
export const routeTree = (RootRoute as any).addChildren([
|
||||
IndexRoute,
|
||||
DictionariesRoute,
|
||||
DictionariesNameRoute,
|
||||
])
|
||||
// @ts-nocheck
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
// This file was automatically generated by TanStack Router.
|
||||
// You should NOT make any changes in this file as it will be overwritten.
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as DictionariesRouteImport } from './routes/dictionaries'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as DictionariesNameRouteImport } from './routes/dictionaries.$name'
|
||||
|
||||
const DictionariesRoute = DictionariesRouteImport.update({
|
||||
id: '/dictionaries',
|
||||
path: '/dictionaries',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const DictionariesNameRoute = DictionariesNameRouteImport.update({
|
||||
id: '/$name',
|
||||
path: '/$name',
|
||||
getParentRoute: () => DictionariesRoute,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/dictionaries': typeof DictionariesRouteWithChildren
|
||||
'/dictionaries/$name': typeof DictionariesNameRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/dictionaries': typeof DictionariesRouteWithChildren
|
||||
'/dictionaries/$name': typeof DictionariesNameRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/dictionaries': typeof DictionariesRouteWithChildren
|
||||
'/dictionaries/$name': typeof DictionariesNameRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/dictionaries' | '/dictionaries/$name'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/dictionaries' | '/dictionaries/$name'
|
||||
id: '__root__' | '/' | '/dictionaries' | '/dictionaries/$name'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
DictionariesRoute: typeof DictionariesRouteWithChildren
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/dictionaries': {
|
||||
id: '/dictionaries'
|
||||
path: '/dictionaries'
|
||||
fullPath: '/dictionaries'
|
||||
preLoaderRoute: typeof DictionariesRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/': {
|
||||
id: '/'
|
||||
path: '/'
|
||||
fullPath: '/'
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/dictionaries/$name': {
|
||||
id: '/dictionaries/$name'
|
||||
path: '/$name'
|
||||
fullPath: '/dictionaries/$name'
|
||||
preLoaderRoute: typeof DictionariesNameRouteImport
|
||||
parentRoute: typeof DictionariesRoute
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface DictionariesRouteChildren {
|
||||
DictionariesNameRoute: typeof DictionariesNameRoute
|
||||
}
|
||||
|
||||
const DictionariesRouteChildren: DictionariesRouteChildren = {
|
||||
DictionariesNameRoute: DictionariesNameRoute,
|
||||
}
|
||||
|
||||
const DictionariesRouteWithChildren = DictionariesRoute._addFileChildren(
|
||||
DictionariesRouteChildren,
|
||||
)
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
DictionariesRoute: DictionariesRouteWithChildren,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
._addFileTypes<FileRouteTypes>()
|
||||
|
||||
@@ -1,36 +1,103 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useRecords } from '@/api/queries'
|
||||
import axios from 'axios'
|
||||
import { useDictionaryDetail, useRecords } from '@/api/queries'
|
||||
import { useCreateRecord, useUpdateRecord, useCloseRecord } from '@/api/mutations'
|
||||
import type { CreateRecordRequest, FlattenedRecord } from '@/api/client'
|
||||
import { Modal } from '@/components/ui/Modal'
|
||||
import { SchemaDrivenForm } from '@/components/form/SchemaDrivenForm'
|
||||
|
||||
export const Route = createFileRoute('/dictionaries/$name')({
|
||||
component: DictionaryDetail,
|
||||
})
|
||||
|
||||
type EditState =
|
||||
| { kind: 'closed' }
|
||||
| { kind: 'create' }
|
||||
| { kind: 'edit'; record: FlattenedRecord }
|
||||
| { kind: 'close-confirm'; record: FlattenedRecord }
|
||||
|
||||
function DictionaryDetail() {
|
||||
const { name } = Route.useParams()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading, error } = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')
|
||||
const detailQuery = useDictionaryDetail(name)
|
||||
const recordsResult = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')
|
||||
const createMut = useCreateRecord(name)
|
||||
const updateMut = useUpdateRecord(name)
|
||||
const closeMut = useCloseRecord(name)
|
||||
|
||||
const [edit, setEdit] = useState<EditState>({ kind: 'closed' })
|
||||
const [closeReason, setCloseReason] = useState('')
|
||||
|
||||
const handleSubmit = (req: CreateRecordRequest) => {
|
||||
if (edit.kind === 'create') {
|
||||
createMut.mutate(req, { onSuccess: () => setEdit({ kind: 'closed' }) })
|
||||
return
|
||||
}
|
||||
if (edit.kind === 'edit') {
|
||||
updateMut.mutate(
|
||||
{ businessKey: edit.record.businessKey, payload: req },
|
||||
{ onSuccess: () => setEdit({ kind: 'closed' }) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (edit.kind !== 'close-confirm') return
|
||||
closeMut.mutate(
|
||||
{ businessKey: edit.record.businessKey, reason: closeReason || undefined },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setEdit({ kind: 'closed' })
|
||||
setCloseReason('')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const activeMutation =
|
||||
edit.kind === 'create' ? createMut : edit.kind === 'edit' ? updateMut : null
|
||||
const serverError = serverErrorMessage(activeMutation?.error)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Link to="/dictionaries" className="text-sm text-zinc-500 hover:text-brand-700">
|
||||
← {t('nav.dictionaries')}
|
||||
</Link>
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold mb-1">{name}</h1>
|
||||
<p className="text-sm text-zinc-500 mb-4">
|
||||
{data?.length ?? 0} {t('dict.list.records')}
|
||||
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold mb-1">
|
||||
{detailQuery.data?.displayName ?? name}
|
||||
</h1>
|
||||
{detailQuery.data?.description && (
|
||||
<p className="text-sm text-zinc-500">{detailQuery.data.description}</p>
|
||||
)}
|
||||
<p className="text-sm text-zinc-500 mt-1">
|
||||
{recordsResult.data?.length ?? 0} {t('dict.list.records')}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'create' })}
|
||||
disabled={!detailQuery.data}
|
||||
className="px-4 py-2 text-sm bg-brand-600 text-white rounded hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
+ {t('dict.action.create')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isLoading && <p className="text-zinc-500">{t('loading')}</p>}
|
||||
{error && <p className="text-red-600">{t('error.failed')}</p>}
|
||||
{recordsResult.isLoading && <p className="text-zinc-500">{t('loading')}</p>}
|
||||
{recordsResult.error && <p className="text-red-600">{t('error.failed')}</p>}
|
||||
|
||||
{data && data.length === 0 && (
|
||||
{recordsResult.data && recordsResult.data.length === 0 && (
|
||||
<p className="text-zinc-500 italic">{t('dict.empty')}</p>
|
||||
)}
|
||||
|
||||
{data && data.length > 0 && (
|
||||
{recordsResult.data && recordsResult.data.length > 0 && (
|
||||
<div className="overflow-x-auto bg-white border border-zinc-200 rounded-lg">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-zinc-50 text-zinc-600">
|
||||
@@ -40,14 +107,15 @@ function DictionaryDetail() {
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.scope')}</th>
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.locale')}</th>
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.validFrom')}</th>
|
||||
<th className="text-right px-4 py-2 font-medium">{t('dict.col.actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.map((r) => (
|
||||
{recordsResult.data.map((r) => (
|
||||
<tr key={r.id} className="border-t border-zinc-100 hover:bg-zinc-50">
|
||||
<td className="px-4 py-2 font-mono text-xs">{r.businessKey}</td>
|
||||
<td className="px-4 py-2">
|
||||
{String((r.data as Record<string, unknown>).name ?? (r.data as Record<string, unknown>).code ?? '—')}
|
||||
{String(r.data.name ?? r.data.code ?? '—')}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<span className="text-xs px-2 py-0.5 rounded bg-zinc-100">{r.dataScope}</span>
|
||||
@@ -56,12 +124,132 @@ function DictionaryDetail() {
|
||||
<td className="px-4 py-2 text-zinc-500 text-xs">
|
||||
{new Date(r.validFrom).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right whitespace-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'edit', record: r })}
|
||||
className="text-xs text-brand-700 hover:underline mr-3"
|
||||
>
|
||||
{t('dict.action.edit')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'close-confirm', record: r })}
|
||||
className="text-xs text-red-600 hover:underline"
|
||||
>
|
||||
{t('dict.action.close')}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={edit.kind === 'create' || edit.kind === 'edit'}
|
||||
onClose={() => setEdit({ kind: 'closed' })}
|
||||
title={
|
||||
edit.kind === 'create'
|
||||
? t('dict.action.create')
|
||||
: edit.kind === 'edit'
|
||||
? `${t('dict.action.edit')}: ${edit.record.businessKey}`
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{detailQuery.data && (edit.kind === 'create' || edit.kind === 'edit') && (
|
||||
<SchemaDrivenForm
|
||||
schema={detailQuery.data.schemaJson}
|
||||
supportedLocales={detailQuery.data.supportedLocales}
|
||||
defaultLocale={detailQuery.data.defaultLocale}
|
||||
mode={edit.kind}
|
||||
isPending={Boolean(activeMutation?.isPending)}
|
||||
serverError={serverError}
|
||||
defaultValues={
|
||||
edit.kind === 'edit'
|
||||
? {
|
||||
businessKey: edit.record.businessKey,
|
||||
data: edit.record.data,
|
||||
validFrom: toDatetimeLocal(edit.record.validFrom),
|
||||
validTo: toDatetimeLocal(edit.record.validTo),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => setEdit({ kind: 'closed' })}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
open={edit.kind === 'close-confirm'}
|
||||
onClose={() => setEdit({ kind: 'closed' })}
|
||||
title={t('dict.confirmClose.title')}
|
||||
widthClass="max-w-md"
|
||||
>
|
||||
{edit.kind === 'close-confirm' && (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-zinc-600">
|
||||
{t('dict.confirmClose.body', { key: edit.record.businessKey })}
|
||||
</p>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 mb-1">
|
||||
{t('dict.confirmClose.reason')}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={closeReason}
|
||||
onChange={(e) => setCloseReason(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-zinc-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||||
placeholder={t('dict.confirmClose.reasonPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
{serverErrorMessage(closeMut.error) && (
|
||||
<div className="px-3 py-2 bg-red-50 border border-red-200 rounded text-sm text-red-700">
|
||||
{serverErrorMessage(closeMut.error)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdit({ kind: 'closed' })}
|
||||
disabled={closeMut.isPending}
|
||||
className="px-4 py-2 text-sm border border-zinc-300 rounded hover:bg-zinc-50 disabled:opacity-50"
|
||||
>
|
||||
{t('form.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClose}
|
||||
disabled={closeMut.isPending}
|
||||
className="px-4 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{closeMut.isPending ? t('form.saving') : t('dict.action.close')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const toDatetimeLocal = (iso: string | undefined): string => {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return ''
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
const serverErrorMessage = (err: unknown): string | null => {
|
||||
if (!err) return null
|
||||
if (axios.isAxiosError(err)) {
|
||||
const data = err.response?.data as { message?: string; error?: string } | undefined
|
||||
if (err.response?.status === 422) return data?.message ?? 'Validation failed'
|
||||
if (err.response?.status === 409) return data?.message ?? 'Conflict — request already in progress'
|
||||
return data?.message ?? data?.error ?? err.message
|
||||
}
|
||||
return err instanceof Error ? err.message : 'Unknown error'
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user