import { Router } from 'express'; import type { Article, Section, Space } from '@prisma/client'; import { parseCheatSheet, renderMarkdown } from '@kb/md'; import type { ArticleDto, ArticleListItem, SectionDto, SpaceDto, TreeResponse, PlaqueColor } from '@kb/shared'; import { canEdit } from '../auth.js'; import { prisma } from '../db.js'; import { HttpError } from '../http.js'; import { search } from '../search.js'; export const contentRouter = Router(); export const toSpaceDto = (s: Space): SpaceDto => ({ id: s.id, name: s.name, slug: s.slug, icon: s.icon, order: s.order }); export const toSectionDto = (s: Section): SectionDto => ({ id: s.id, spaceId: s.spaceId, name: s.name, slug: s.slug, code: s.code, color: s.color as PlaqueColor, icon: s.icon, order: s.order, }); type ArticleWithAssets = Article & { assets: { size: number }[] }; export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({ id: a.id, slug: a.slug, title: a.title, summary: a.summary, sectionId: a.sectionId, order: a.order, tags: a.tags, equipment: a.equipment, docCode: a.docCode, pinned: a.pinned, status: a.status, visibility: a.visibility, version: a.version, updatedAt: a.updatedAt.toISOString(), imageCount: a.assets.length, bytes: a.assets.reduce((n, x) => n + x.size, 0), }); // Всё дерево одним запросом: пространства, разделы и список статей (без текста). // Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны, // а для офлайна один ответ кешировать проще. // Кто что видит: без входа только опубликованные статьи с visibility PUBLIC; // читатель: все опубликованные; редактор и админ: ещё и черновики. contentRouter.get('/tree', async (req, res) => { const where = !req.user ? { status: 'PUBLISHED' as const, visibility: 'PUBLIC' as const } : canEdit(req.user) ? {} : { status: 'PUBLISHED' as const }; const [spaces, allSections, articles] = await Promise.all([ prisma.space.findMany({ orderBy: { order: 'asc' } }), prisma.section.findMany({ orderBy: { order: 'asc' } }), prisma.article.findMany({ where, orderBy: [{ order: 'asc' }, { title: 'asc' }], include: { assets: { select: { size: true } } }, }), ]); // Гостю не показываем даже названия разделов, в которых нет публичных статей const used = new Set(articles.map((a) => a.sectionId)); const sections = req.user ? allSections : allSections.filter((s) => used.has(s.id)); const body: TreeResponse = { spaces: req.user || sections.length ? spaces.map(toSpaceDto) : [], sections: sections.map(toSectionDto), articles: articles.map(toListItem), }; res.json(body); }); contentRouter.get('/articles/:slug', async (req, res) => { const art = await prisma.article.findUnique({ where: { slug: req.params.slug }, include: { assets: { select: { size: true } }, attachments: { orderBy: { createdAt: 'asc' } }, author: { select: { name: true } }, }, }); if (!art || (art.status !== 'PUBLISHED' && !canEdit(req.user))) throw new HttpError(404, 'Статья не найдена'); // Закрытая статья без входа: 401, клиент покажет экран входа if (!req.user && art.visibility !== 'PUBLIC') throw new HttpError(401, 'Нужно войти'); // Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье const { figures, toc } = renderMarkdown(art.bodyMd); const cheat = art.pinned ? parseCheatSheet(art.bodyMd) : null; const body: ArticleDto = { ...toListItem(art), bodyMd: art.bodyMd, bodyHtml: art.bodyHtml, attachments: art.attachments.map((a) => ({ id: a.id, filename: a.filename, url: `/uploads/${a.path}`, size: a.size, })), images: figures.flatMap((f) => [f.thumb, f.full]), authorName: art.author?.name ?? null, toc, cheat: cheat?.ok ? cheat : null, }; res.json(body); }); // Поиск. Пустой запрос: пустой ответ (подсказки рисует клиент). contentRouter.get('/search', async (req, res) => { const q = String(req.query.q ?? '').slice(0, 100); res.json(await search(q, !req.user)); });