feat: categories table with full CRUD

- Fills out placeholder categories table with all fields
- Trilingual titles, status enum, difficulty level, auto-timestamps
- ALTER TABLE IF NOT EXISTS for safe migration on existing table
- /api/categories CRUD route, word_ids included in responses

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-20 14:10:22 +02:00
parent 8751d7ceae
commit 8bd4240ea9
4 changed files with 164 additions and 10 deletions

View File

@@ -120,12 +120,21 @@ words ──────────── word_pictures ───────
| `word_id` | `UUID` FK → `words.id` CASCADE | | `word_id` | `UUID` FK → `words.id` CASCADE |
| `picture_id` | `UUID` FK → `pictures.id` CASCADE | | `picture_id` | `UUID` FK → `pictures.id` CASCADE |
### Table: `categories` (Platzhalter — Felder folgen) ### Table: `categories`
| Column | Type |
|---|---| | Column | Type | Default | Description |
| `id` | `UUID` PK | |---|---|---|---|
| `created_at` | `TIMESTAMPTZ` | | `id` | `UUID` | `gen_random_uuid()` | Primary key |
| `updated_at` | `TIMESTAMPTZ` | | `titel_de` | `TEXT` | `null` | German title |
| `titel_en` | `TEXT` | `null` | English title |
| `titel_se` | `TEXT` | `null` | Swedish title |
| `status` | `VARCHAR(20)` | `requested` | `requested` · `blocked` · `published` |
| `difficulty_level` | `SMALLINT` | `null` | 150 |
| `requested_at` | `TIMESTAMPTZ` | `NOW()` on insert | Auto-set on create |
| `published_at` | `TIMESTAMPTZ` | `null` | Auto-set when status → `published` |
| `blocked_at` | `TIMESTAMPTZ` | `null` | Auto-set when status → `blocked` |
| `created_at` | `TIMESTAMPTZ` | `NOW()` | Auto-set on insert |
| `updated_at` | `TIMESTAMPTZ` | `NOW()` | Auto-updated on every change (trigger) |
### Table: `word_categories` (Junction) ### Table: `word_categories` (Junction)
| Column | Type | | Column | Type |
@@ -279,6 +288,24 @@ curl -X PATCH "$BASE/api/words/<ID>" \
--- ---
### Categories
#### `GET /api/categories` — Liste (`?status=requested&limit=50&offset=0`)
#### `GET /api/categories/:id` — Einzelne Kategorie inkl. `word_ids`
#### `POST /api/categories` — Neue Kategorie anlegen
```bash
curl -X POST "$BASE/api/categories" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"titel_de": "Tiere", "titel_en": "Animals", "titel_se": "Djur", "difficulty_level": 10}'
```
#### `PATCH /api/categories/:id` — Felder aktualisieren (Status setzt Timestamp automatisch)
#### `DELETE /api/categories/:id` — Kategorie löschen (entfernt auch alle Verknüpfungen)
---
### Utilities ### Utilities
#### `GET /api/tables` #### `GET /api/tables`

View File

@@ -68,15 +68,38 @@ async function migrate() {
) )
`); `);
// categories (Platzhalter — Felder folgen im nächsten Schritt)
await query(` await query(`
CREATE TABLE IF NOT EXISTS categories ( CREATE TABLE IF NOT EXISTS categories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
titel_de TEXT,
titel_en TEXT,
titel_se TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'requested'
CHECK (status IN ('requested', 'blocked', 'published')),
difficulty_level SMALLINT CHECK (difficulty_level BETWEEN 1 AND 50),
requested_at TIMESTAMPTZ,
published_at TIMESTAMPTZ,
blocked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
) )
`); `);
// Felder nachrüsten falls Tabelle schon als Platzhalter existiert
const catCols = ['titel_de TEXT', 'titel_en TEXT', 'titel_se TEXT',
"status VARCHAR(20) NOT NULL DEFAULT 'requested'",
'difficulty_level SMALLINT', 'requested_at TIMESTAMPTZ',
'published_at TIMESTAMPTZ', 'blocked_at TIMESTAMPTZ'];
for (const col of catCols) {
const name = col.split(' ')[0];
await query(`ALTER TABLE categories ADD COLUMN IF NOT EXISTS ${col}`).catch(() => {});
// CHECK constraint nur wenn noch nicht vorhanden
if (name === 'status') {
await query(`ALTER TABLE categories DROP CONSTRAINT IF EXISTS categories_status_check`).catch(() => {});
await query(`ALTER TABLE categories ADD CONSTRAINT categories_status_check CHECK (status IN ('requested', 'blocked', 'published'))`).catch(() => {});
}
}
await query(` await query(`
DROP TRIGGER IF EXISTS categories_updated_at ON categories; DROP TRIGGER IF EXISTS categories_updated_at ON categories;
CREATE TRIGGER categories_updated_at CREATE TRIGGER categories_updated_at

View File

@@ -26,6 +26,7 @@ app.get('/health', async (req, res) => {
app.use('/api', auth, require('./routes/index')); app.use('/api', auth, require('./routes/index'));
app.use('/api/pictures', auth, require('./routes/pictures')); app.use('/api/pictures', auth, require('./routes/pictures'));
app.use('/api/words', auth, require('./routes/words')); app.use('/api/words', auth, require('./routes/words'));
app.use('/api/categories', auth, require('./routes/categories'));
// 404 // 404
app.use((req, res) => { app.use((req, res) => {

103
src/routes/categories.js Normal file
View File

@@ -0,0 +1,103 @@
const router = require('express').Router();
const { query } = require('../db');
const STATUSES = ['requested', 'blocked', 'published'];
const STATUS_TIMESTAMP = {
requested: 'requested_at',
published: 'published_at',
blocked: 'blocked_at',
};
// GET /api/categories
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 c.status = $3` : '';
if (status) params.push(status);
const result = await query(
`SELECT c.*,
COALESCE(json_agg(DISTINCT w.id) FILTER (WHERE w.id IS NOT NULL), '[]') AS word_ids
FROM categories c
LEFT JOIN word_categories wc ON wc.category_id = c.id
LEFT JOIN words w ON w.id = wc.word_id
${where}
GROUP BY c.id
ORDER BY c.created_at DESC
LIMIT $1 OFFSET $2`,
params
);
res.json(result.rows);
} catch (err) { next(err); }
});
// GET /api/categories/:id
router.get('/:id', async (req, res, next) => {
try {
const result = await query(
`SELECT c.*,
COALESCE(json_agg(DISTINCT w.id) FILTER (WHERE w.id IS NOT NULL), '[]') AS word_ids
FROM categories c
LEFT JOIN word_categories wc ON wc.category_id = c.id
LEFT JOIN words w ON w.id = wc.word_id
WHERE c.id = $1
GROUP BY c.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/categories
router.post('/', async (req, res, next) => {
try {
const { titel_de, titel_en, titel_se, difficulty_level } = req.body;
const result = await query(
`INSERT INTO categories (titel_de, titel_en, titel_se, difficulty_level, requested_at)
VALUES ($1, $2, $3, $4, NOW()) RETURNING *`,
[titel_de || null, titel_en || null, titel_se || null, difficulty_level || null]
);
res.status(201).json({ ...result.rows[0], word_ids: [] });
} catch (err) { next(err); }
});
// PATCH /api/categories/:id
router.patch('/:id', async (req, res, next) => {
try {
const allowed = ['titel_de', 'titel_en', 'titel_se', '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(', ')}` });
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 categories 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/categories/:id
router.delete('/:id', async (req, res, next) => {
try {
const result = await query('DELETE FROM categories 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); }
});
module.exports = router;