Files
snakkimo-API/src/routes/words.js
admin 10570786e9 Add languages, user_names, users_public tables and routes; fix _se→_sv rename
- Fix broken rename migration array (sed had corrupted from values to _sv)
- Add languages table with status lifecycle and trilingual titles
- Add user_names table with unique lowercase index
- Add users_public table linking to user_names and languages (native/target)
- Wire all three new routes under /api/languages, /api/user-names, /api/users-public

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 13:47:52 +02:00

155 lines
5.5 KiB
JavaScript

const router = require('express').Router();
const { query } = require('../db');
const STATUSES = ['requested', 'translated', 'generated', 'blocked', 'published'];
const STATUS_TIMESTAMP = {
requested: 'requested_at',
published: 'published_at',
blocked: 'blocked_at',
};
// GET /api/words
router.get('/', async (req, res, next) => {
try {
const { status, limit = 50, offset = 0 } = req.query;
const params = [Math.min(parseInt(limit), 500), parseInt(offset)];
const where = status ? `WHERE w.status = $3` : '';
if (status) params.push(status);
const result = await query(
`SELECT w.*,
COALESCE(json_agg(DISTINCT p.id) FILTER (WHERE p.id IS NOT NULL), '[]') AS picture_ids,
COALESCE(json_agg(DISTINCT c.id) FILTER (WHERE c.id IS NOT NULL), '[]') AS category_ids
FROM words w
LEFT JOIN word_pictures wp ON wp.word_id = w.id
LEFT JOIN pictures p ON p.id = wp.picture_id
LEFT JOIN word_categories wc ON wc.word_id = w.id
LEFT JOIN categories c ON c.id = wc.category_id
${where}
GROUP BY w.id
ORDER BY w.created_at DESC
LIMIT $1 OFFSET $2`,
params
);
res.json(result.rows);
} catch (err) { next(err); }
});
// GET /api/words/:id
router.get('/:id', async (req, res, next) => {
try {
const result = await query(
`SELECT w.*,
COALESCE(json_agg(DISTINCT p.id) FILTER (WHERE p.id IS NOT NULL), '[]') AS picture_ids,
COALESCE(json_agg(DISTINCT c.id) FILTER (WHERE c.id IS NOT NULL), '[]') AS category_ids
FROM words w
LEFT JOIN word_pictures wp ON wp.word_id = w.id
LEFT JOIN pictures p ON p.id = wp.picture_id
LEFT JOIN word_categories wc ON wc.word_id = w.id
LEFT JOIN categories c ON c.id = wc.category_id
WHERE w.id = $1
GROUP BY w.id`,
[req.params.id]
);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.json(result.rows[0]);
} catch (err) { next(err); }
});
// POST /api/words
router.post('/', async (req, res, next) => {
try {
const { titel_de, titel_en, titel_sv, difficulty_level } = req.body;
const result = await query(
`INSERT INTO words (titel_de, titel_en, titel_sv, difficulty_level, requested_at)
VALUES ($1, $2, $3, $4, NOW()) RETURNING *`,
[titel_de || null, titel_en || null, titel_sv || null, difficulty_level || null]
);
res.status(201).json({ ...result.rows[0], picture_ids: [], category_ids: [] });
} catch (err) { next(err); }
});
// PATCH /api/words/:id
router.patch('/:id', async (req, res, next) => {
try {
const allowed = ['titel_de', 'titel_en', 'titel_sv', 'status',
'difficulty_level', 'requested_at', 'published_at', 'blocked_at'];
const fields = Object.keys(req.body).filter(k => allowed.includes(k));
if (!fields.length) return res.status(400).json({ error: 'No valid fields provided' });
if (req.body.status && !STATUSES.includes(req.body.status))
return res.status(400).json({ error: `status must be one of: ${STATUSES.join(', ')}` });
// Auto-timestamp bei Statuswechsel
const tsField = STATUS_TIMESTAMP[req.body.status];
if (tsField && !req.body[tsField]) {
fields.push(tsField);
req.body[tsField] = new Date().toISOString();
}
const setClauses = fields.map((f, i) => `${f} = $${i + 1}`).join(', ');
const values = [...fields.map(f => req.body[f]), req.params.id];
const result = await query(
`UPDATE words SET ${setClauses} WHERE id = $${fields.length + 1} RETURNING *`,
values
);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.json(result.rows[0]);
} catch (err) { next(err); }
});
// DELETE /api/words/:id
router.delete('/:id', async (req, res, next) => {
try {
const result = await query('DELETE FROM words WHERE id = $1 RETURNING id', [req.params.id]);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.status(204).end();
} catch (err) { next(err); }
});
// POST /api/words/:id/pictures/:pictureId — Bild verknüpfen
router.post('/:id/pictures/:pictureId', async (req, res, next) => {
try {
await query(
`INSERT INTO word_pictures (word_id, picture_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[req.params.id, req.params.pictureId]
);
res.status(204).end();
} catch (err) { next(err); }
});
// DELETE /api/words/:id/pictures/:pictureId — Bild-Verknüpfung entfernen
router.delete('/:id/pictures/:pictureId', async (req, res, next) => {
try {
await query(
`DELETE FROM word_pictures WHERE word_id = $1 AND picture_id = $2`,
[req.params.id, req.params.pictureId]
);
res.status(204).end();
} catch (err) { next(err); }
});
// POST /api/words/:id/categories/:categoryId — Kategorie verknüpfen
router.post('/:id/categories/:categoryId', async (req, res, next) => {
try {
await query(
`INSERT INTO word_categories (word_id, category_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[req.params.id, req.params.categoryId]
);
res.status(204).end();
} catch (err) { next(err); }
});
// DELETE /api/words/:id/categories/:categoryId — Kategorie-Verknüpfung entfernen
router.delete('/:id/categories/:categoryId', async (req, res, next) => {
try {
await query(
`DELETE FROM word_categories WHERE word_id = $1 AND category_id = $2`,
[req.params.id, req.params.categoryId]
);
res.status(204).end();
} catch (err) { next(err); }
});
module.exports = router;