feat(admin-ui): minimal React+Vite+TanStack scaffolding
- Vite 7 + React 19 + TanStack Router (file-based) + TanStack Query - Tailwind v4 (CSS-first config, OKLCH brand colors) - i18next + react-i18next с RU/EN switcher в header - Axios client с Accept-Language interceptor + JWT placeholder - 2 pages: /dictionaries (list cards) + /dictionaries/$name (records table) - Dockerfile (node build + nginx serving + API proxy) - README + .gitignore Backend: - Новый GET /api/v1/dictionaries в read-api (DictionaryListController), фильтрует по доступному scope через ScopeContext - DictionaryListItem DTO без heavy schema_json routeTree.gen.ts — stub; реальное содержимое генерится Vite plugin'ом при первом 'pnpm dev'.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
.vite
|
||||
*.log
|
||||
.env.local
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM repo.nstart.cloud/library/node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json ./
|
||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store pnpm install --no-frozen-lockfile
|
||||
COPY . .
|
||||
RUN pnpm build
|
||||
|
||||
FROM repo.nstart.cloud/library/nginx:1.27-alpine
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,30 @@
|
||||
# Ordinis Admin UI
|
||||
|
||||
React 19 + Vite 7 + TanStack Router + TanStack Query + Tailwind v4 + i18next.
|
||||
|
||||
## Локально
|
||||
|
||||
```bash
|
||||
cd ordinis-admin-ui
|
||||
pnpm install
|
||||
# .env.local: VITE_API_PROXY=http://localhost:8081 (port-forward read-api)
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## Контракт API
|
||||
|
||||
- `GET /api/v1/dictionaries` (read-api) — список справочников
|
||||
- `GET /api/v1/{dictionaryName}/records` (read-api) — записи с локализацией
|
||||
- `POST /api/v1/dictionaries` (writer) — создание справочника (TODO в UI)
|
||||
- `POST /api/v1/dictionaries/{name}/records` (writer) — создание записи (TODO в UI)
|
||||
|
||||
## Сборка / Docker
|
||||
|
||||
```bash
|
||||
docker build -t repo.nstart.cloud/terravault/ordinis-admin-ui:dev .
|
||||
docker run --rm -p 8088:80 repo.nstart.cloud/terravault/ordinis-admin-ui:dev
|
||||
# → http://localhost:8088
|
||||
```
|
||||
|
||||
В кластере nginx проксирует `/api/v1/*` в `ordinis-read-api` (GET) и
|
||||
`ordinis-app` (POST/PUT/PATCH/DELETE).
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ru-RU">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ordinis Admin — НСИ ЦУОД</title>
|
||||
</head>
|
||||
<body class="bg-zinc-50 text-zinc-900">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
# SPA history fallback
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# API proxy в read-api/writer (через k8s service DNS).
|
||||
# Реальный endpoint задаётся через env-template или ENV в pod, в v1
|
||||
# просто проксируем на ordinis-read-api (только GET) и ordinis-app (write).
|
||||
location /api/v1/dictionaries {
|
||||
# POST/PUT идут в writer, GET — в read-api. Простое разделение по methods:
|
||||
if ($request_method ~ ^(POST|PUT|PATCH|DELETE)$) {
|
||||
proxy_pass http://ordinis-app:80;
|
||||
}
|
||||
proxy_pass http://ordinis-read-api:80;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_pass_request_headers on;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/[^/]+/records {
|
||||
if ($request_method ~ ^(POST|PUT|PATCH|DELETE)$) {
|
||||
proxy_pass http://ordinis-app:80;
|
||||
}
|
||||
proxy_pass http://ordinis-read-api:80;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_pass_request_headers on;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "ordinis-admin-ui",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview --host 0.0.0.0 --port 4173"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@tanstack/react-router": "^1.86.0",
|
||||
"axios": "^1.7.9",
|
||||
"i18next": "^24.0.5",
|
||||
"i18next-browser-languagedetector": "^8.0.2",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-i18next": "^15.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tanstack/router-vite-plugin": "^1.86.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"tailwindcss": "^4.0.0-beta.7",
|
||||
"@tailwindcss/vite": "^4.0.0-beta.7",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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,
|
||||
})
|
||||
|
||||
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
|
||||
})
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(resp) => resp,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('ordinis.token')
|
||||
}
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
export type DictionaryDefinition = {
|
||||
id: string
|
||||
name: string
|
||||
displayName?: string
|
||||
description?: string
|
||||
scope: 'PUBLIC' | 'INTERNAL' | 'RESTRICTED'
|
||||
schemaVersion: string
|
||||
bundle: string
|
||||
supportedLocales: string[]
|
||||
defaultLocale: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type FlattenedRecord = {
|
||||
id: string
|
||||
businessKey: string
|
||||
data: Record<string, unknown>
|
||||
dataScope: 'PUBLIC' | 'INTERNAL' | 'RESTRICTED'
|
||||
validFrom: string
|
||||
validTo: string
|
||||
_meta?: { locale?: string }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useQuery, queryOptions } from '@tanstack/react-query'
|
||||
import { apiClient, type DictionaryDefinition, type FlattenedRecord } from './client'
|
||||
|
||||
export const dictionariesQuery = queryOptions({
|
||||
queryKey: ['dictionaries'],
|
||||
queryFn: async (): Promise<DictionaryDefinition[]> => {
|
||||
const { data } = await apiClient.get<DictionaryDefinition[]>('/dictionaries')
|
||||
return data
|
||||
},
|
||||
})
|
||||
|
||||
export const recordsQuery = (dictionaryName: string, scopeCsv: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['records', dictionaryName, scopeCsv],
|
||||
queryFn: async (): Promise<FlattenedRecord[]> => {
|
||||
const { data } = await apiClient.get<FlattenedRecord[]>(
|
||||
`/${dictionaryName}/records`,
|
||||
{ params: { as_scope: scopeCsv } },
|
||||
)
|
||||
return data
|
||||
},
|
||||
})
|
||||
|
||||
export const useDictionaries = () => useQuery(dictionariesQuery)
|
||||
export const useRecords = (dictionaryName: string, scopeCsv: string) =>
|
||||
useQuery(recordsQuery(dictionaryName, scopeCsv))
|
||||
@@ -0,0 +1,46 @@
|
||||
import i18n from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
import LanguageDetector from 'i18next-browser-languagedetector'
|
||||
|
||||
i18n
|
||||
.use(LanguageDetector)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
fallbackLng: 'ru-RU',
|
||||
supportedLngs: ['ru-RU', 'en-US'],
|
||||
interpolation: { escapeValue: false },
|
||||
resources: {
|
||||
'ru-RU': {
|
||||
translation: {
|
||||
'app.title': 'Ordinis НСИ ЦУОД',
|
||||
'nav.dictionaries': 'Справочники',
|
||||
'header.scope': 'Доступный scope',
|
||||
'dict.empty': 'В этом справочнике пока нет записей',
|
||||
'dict.col.businessKey': 'Бизнес-ключ',
|
||||
'dict.col.scope': 'Scope',
|
||||
'dict.col.validFrom': 'Действует с',
|
||||
'dict.col.locale': 'Локаль',
|
||||
'dict.list.records': 'записей',
|
||||
'loading': 'Загрузка...',
|
||||
'error.failed': 'Не удалось загрузить данные',
|
||||
},
|
||||
},
|
||||
'en-US': {
|
||||
translation: {
|
||||
'app.title': 'Ordinis MDM',
|
||||
'nav.dictionaries': 'Dictionaries',
|
||||
'header.scope': 'Allowed scope',
|
||||
'dict.empty': 'No records in this dictionary yet',
|
||||
'dict.col.businessKey': 'Business key',
|
||||
'dict.col.scope': 'Scope',
|
||||
'dict.col.validFrom': 'Valid from',
|
||||
'dict.col.locale': 'Locale',
|
||||
'dict.list.records': 'records',
|
||||
'loading': 'Loading...',
|
||||
'error.failed': 'Failed to load data',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export default i18n
|
||||
@@ -0,0 +1,29 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RouterProvider, createRouter } from '@tanstack/react-router'
|
||||
import { routeTree } from './routeTree.gen'
|
||||
import './i18n'
|
||||
import './styles.css'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { staleTime: 30_000, retry: 1 },
|
||||
},
|
||||
})
|
||||
|
||||
const router = createRouter({ routeTree, context: { queryClient } })
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface Register {
|
||||
router: typeof router
|
||||
}
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
// АВТОГЕНЕРИРУЕТСЯ TanStackRouterVite plugin'ом при `pnpm dev` или `pnpm build`.
|
||||
// Этот stub нужен только для первой компиляции TS — реальное содержимое
|
||||
// (импорты route'ов, типы) появится после первого запуска vite.
|
||||
//
|
||||
// После первого запуска можно либо .gitignore'ить routeTree.gen.ts, либо
|
||||
// держать его в репо обновлённым (рекомендация TanStack).
|
||||
//
|
||||
// eslint-disable
|
||||
// @ts-nocheck
|
||||
import { Route as RootRoute } from './routes/__root'
|
||||
export const routeTree = (RootRoute as unknown as { addChildren: (c: unknown[]) => unknown }).addChildren([])
|
||||
@@ -0,0 +1,48 @@
|
||||
import { createRootRouteWithContext, Link, Outlet } from '@tanstack/react-router'
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
|
||||
component: RootLayout,
|
||||
})
|
||||
|
||||
function RootLayout() {
|
||||
const { t, i18n } = useTranslation()
|
||||
return (
|
||||
<div className="min-h-full flex flex-col">
|
||||
<header className="border-b border-zinc-200 bg-white">
|
||||
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center gap-6">
|
||||
<Link to="/" className="font-semibold text-lg text-brand-700">
|
||||
{t('app.title')}
|
||||
</Link>
|
||||
<nav className="flex gap-4 text-sm">
|
||||
<Link
|
||||
to="/dictionaries"
|
||||
className="text-zinc-600 hover:text-brand-700"
|
||||
activeProps={{ className: 'text-brand-700 font-medium' }}
|
||||
>
|
||||
{t('nav.dictionaries')}
|
||||
</Link>
|
||||
</nav>
|
||||
<div className="ml-auto flex items-center gap-2 text-sm">
|
||||
<button
|
||||
onClick={() => i18n.changeLanguage('ru-RU')}
|
||||
className={`px-2 py-1 rounded ${i18n.language === 'ru-RU' ? 'bg-brand-50 text-brand-700' : 'text-zinc-500'}`}
|
||||
>
|
||||
RU
|
||||
</button>
|
||||
<button
|
||||
onClick={() => i18n.changeLanguage('en-US')}
|
||||
className={`px-2 py-1 rounded ${i18n.language === 'en-US' ? 'bg-brand-50 text-brand-700' : 'text-zinc-500'}`}
|
||||
>
|
||||
EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main className="flex-1 max-w-6xl mx-auto w-full px-6 py-8">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useRecords } from '@/api/queries'
|
||||
|
||||
export const Route = createFileRoute('/dictionaries/$name')({
|
||||
component: DictionaryDetail,
|
||||
})
|
||||
|
||||
function DictionaryDetail() {
|
||||
const { name } = Route.useParams()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading, error } = useRecords(name, 'PUBLIC,INTERNAL,RESTRICTED')
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<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')}
|
||||
</p>
|
||||
|
||||
{isLoading && <p className="text-zinc-500">{t('loading')}</p>}
|
||||
{error && <p className="text-red-600">{t('error.failed')}</p>}
|
||||
|
||||
{data && data.length === 0 && (
|
||||
<p className="text-zinc-500 italic">{t('dict.empty')}</p>
|
||||
)}
|
||||
|
||||
{data && 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">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-2 font-medium">{t('dict.col.businessKey')}</th>
|
||||
<th className="text-left px-4 py-2 font-medium">name / code</th>
|
||||
<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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{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 ?? '—')}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<span className="text-xs px-2 py-0.5 rounded bg-zinc-100">{r.dataScope}</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-zinc-500 text-xs">{r._meta?.locale ?? '—'}</td>
|
||||
<td className="px-4 py-2 text-zinc-500 text-xs">
|
||||
{new Date(r.validFrom).toLocaleDateString()}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useDictionaries } from '@/api/queries'
|
||||
|
||||
export const Route = createFileRoute('/dictionaries')({
|
||||
component: DictionariesPage,
|
||||
})
|
||||
|
||||
function DictionariesPage() {
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading, error } = useDictionaries()
|
||||
|
||||
if (isLoading) return <p className="text-zinc-500">{t('loading')}</p>
|
||||
if (error) return <p className="text-red-600">{t('error.failed')}: {String(error)}</p>
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{(data ?? []).map((d) => (
|
||||
<Link
|
||||
key={d.id}
|
||||
to="/dictionaries/$name"
|
||||
params={{ name: d.name }}
|
||||
className="border border-zinc-200 rounded-lg p-4 hover:border-brand-500 hover:shadow-sm transition bg-white"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<h2 className="font-semibold text-zinc-900">{d.displayName ?? d.name}</h2>
|
||||
<span className="text-xs px-2 py-0.5 rounded bg-brand-50 text-brand-700">
|
||||
{d.scope}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-zinc-600 line-clamp-2 mb-2">{d.description}</p>
|
||||
<div className="flex gap-2 text-xs text-zinc-400">
|
||||
<span>v{d.schemaVersion}</span>
|
||||
<span>·</span>
|
||||
<span>{d.bundle}</span>
|
||||
<span>·</span>
|
||||
<span>{d.supportedLocales.join(', ')}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/')({
|
||||
beforeLoad: () => {
|
||||
throw redirect({ to: '/dictionaries' })
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
@theme {
|
||||
--color-brand-50: oklch(0.97 0.02 250);
|
||||
--color-brand-500: oklch(0.55 0.16 250);
|
||||
--color-brand-700: oklch(0.42 0.18 250);
|
||||
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".",
|
||||
"paths": { "@/*": ["src/*"] }
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { TanStackRouterVite } from '@tanstack/router-vite-plugin'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
TanStackRouterVite({ routesDirectory: 'src/routes', generatedRouteTree: 'src/routeTree.gen.ts' }),
|
||||
react(),
|
||||
tailwindcss(),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.VITE_API_PROXY ?? 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package cloud.nstart.terravault.ordinis.readapi.dto;
|
||||
|
||||
import cloud.nstart.terravault.ordinis.domain.DataScope;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Облегчённое представление справочника для list-эндпоинта (без schema_json,
|
||||
* чтобы не таскать тяжёлые JSON Schema на главную). Полная схема — отдельным
|
||||
* GET /api/v1/dictionaries/{name}.
|
||||
*/
|
||||
public record DictionaryListItem(
|
||||
UUID id,
|
||||
String name,
|
||||
String displayName,
|
||||
String description,
|
||||
DataScope scope,
|
||||
String schemaVersion,
|
||||
String bundle,
|
||||
List<String> supportedLocales,
|
||||
String defaultLocale,
|
||||
OffsetDateTime createdAt,
|
||||
OffsetDateTime updatedAt) {}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package cloud.nstart.terravault.ordinis.readapi.web;
|
||||
|
||||
import cloud.nstart.terravault.ordinis.auth.ScopeContext;
|
||||
import cloud.nstart.terravault.ordinis.domain.DataScope;
|
||||
import cloud.nstart.terravault.ordinis.domain.definition.DictionaryDefinition;
|
||||
import cloud.nstart.terravault.ordinis.domain.definition.DictionaryDefinitionRepository;
|
||||
import cloud.nstart.terravault.ordinis.readapi.dto.DictionaryListItem;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* GET /api/v1/dictionaries — список доступных справочников. Фильтрация по
|
||||
* scope такая же, как для records: возвращаются только справочники со scope ⊆
|
||||
* текущим разрешённым scope клиенту.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/dictionaries")
|
||||
public class DictionaryListController {
|
||||
|
||||
private final DictionaryDefinitionRepository repository;
|
||||
private final ScopeContext scopeContext;
|
||||
|
||||
public DictionaryListController(
|
||||
DictionaryDefinitionRepository repository, ScopeContext scopeContext) {
|
||||
this.repository = repository;
|
||||
this.scopeContext = scopeContext;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<DictionaryListItem> list(
|
||||
@RequestParam(value = "as_scope", required = false) String asScope) {
|
||||
|
||||
Set<DataScope> scopes = scopeContext.resolveForRead(asScope);
|
||||
return repository.findAll().stream()
|
||||
.filter(d -> scopes.contains(d.getScope()))
|
||||
.map(DictionaryListController::toItem)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static DictionaryListItem toItem(DictionaryDefinition d) {
|
||||
return new DictionaryListItem(
|
||||
d.getId(),
|
||||
d.getName(),
|
||||
d.getDisplayName(),
|
||||
d.getDescription(),
|
||||
d.getScope(),
|
||||
d.getSchemaVersion(),
|
||||
d.getBundle(),
|
||||
d.getSupportedLocales() == null ? List.of() : List.of(d.getSupportedLocales()),
|
||||
d.getDefaultLocale(),
|
||||
d.getCreatedAt(),
|
||||
d.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user