fix(autogen/topics): endpoint читает из blog_topics БД вместо хардкода TOPIC_BANK

GET /api/autogen/topics теперь возвращает темы из blog_topics (свободные,
sorted by priority DESC), backward-compat: возвращает строки как раньше.
Fallback на TOPIC_BANK если для категории нет тем в БД.
This commit is contained in:
Aleksei Pavlov
2026-06-21 21:00:08 +03:00
parent 45c3f2b562
commit 48e0bae495
+41 -3
View File
@@ -71,9 +71,47 @@ router.delete('/queue/:id', async (req, res) => {
} catch (err) { res.status(500).json({ error: err.message }); } } catch (err) { res.status(500).json({ error: err.message }); }
}); });
// GET /api/autogen/topics — банк тем // GET /api/autogen/topics — банк тем из БД (с fallback на TOPIC_BANK)
router.get('/topics', async (_, res) => { // ?category=slug — только одна категория
res.json(TOPIC_BANK); // ?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; module.exports = router;