From 48e0bae49582a07d11f580419f57ea289e460882 Mon Sep 17 00:00:00 2001 From: Aleksei Pavlov Date: Sun, 21 Jun 2026 21:00:08 +0300 Subject: [PATCH] =?UTF-8?q?fix(autogen/topics):=20endpoint=20=D1=87=D0=B8?= =?UTF-8?q?=D1=82=D0=B0=D0=B5=D1=82=20=D0=B8=D0=B7=20blog=5Ftopics=20?= =?UTF-8?q?=D0=91=D0=94=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D1=85?= =?UTF-8?q?=D0=B0=D1=80=D0=B4=D0=BA=D0=BE=D0=B4=D0=B0=20TOPIC=5FBANK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /api/autogen/topics теперь возвращает темы из blog_topics (свободные, sorted by priority DESC), backward-compat: возвращает строки как раньше. Fallback на TOPIC_BANK если для категории нет тем в БД. --- src/routes/autogen.js | 44 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/routes/autogen.js b/src/routes/autogen.js index efbbfc2..483f26c 100644 --- a/src/routes/autogen.js +++ b/src/routes/autogen.js @@ -71,9 +71,47 @@ router.delete('/queue/:id', async (req, res) => { } catch (err) { res.status(500).json({ error: err.message }); } }); -// GET /api/autogen/topics — банк тем -router.get('/topics', async (_, res) => { - res.json(TOPIC_BANK); +// GET /api/autogen/topics — банк тем из БД (с fallback на TOPIC_BANK) +// ?category=slug — только одна категория +// ?limit=N — максимум N тем на категорию (default 20) +// ?free=true — только неиспользованные (default true) +router.get('/topics', async (req, res) => { + try { + const { query } = require('../config/db'); + const onlyFree = req.query.free !== 'false'; + const limit = Math.min(parseInt(req.query.limit, 10) || 20, 100); + const catFilter = req.query.category || null; + + const { rows } = await query(` + SELECT category, topic, priority, is_used, source + FROM blog_topics + WHERE ($1::text IS NULL OR category = $1) + AND ($2 = false OR is_used = false) + ORDER BY category, priority DESC, created_at ASC + LIMIT $3 + `, [catFilter, onlyFree, limit * 10]); // берём с запасом, потом нарежем + + // Группируем по категории, ограничиваем до limit на категорию + const grouped = {}; + for (const row of rows) { + if (!grouped[row.category]) grouped[row.category] = []; + if (grouped[row.category].length < limit) { + grouped[row.category].push(row.topic); + } + } + + // Если для какой-то категории нет тем в БД — fallback на TOPIC_BANK + for (const [cat, bank] of Object.entries(TOPIC_BANK)) { + if (!grouped[cat] || grouped[cat].length === 0) { + grouped[cat] = [...bank]; + } + } + + res.json(grouped); + } catch (err) { + console.error('[autogen/topics]', err.message); + res.json(TOPIC_BANK); // fallback + } }); module.exports = router;