feat: pictures table, Hetzner S3 upload/delete, auto-migration

- pictures table with UUID, status enum, timestamps, blurhash, design
- Auto-trigger updates updated_at on every row change
- POST /api/pictures/:id/upload  → upload file to Hetzner snakkimo bucket
- DELETE /api/pictures/:id       → removes DB row + Hetzner file
- PATCH /api/pictures/:id        → auto-sets published/blocked timestamps
- Migration runs on every server start (idempotent)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-20 13:39:16 +02:00
parent b82a468197
commit 0f35459b86
6 changed files with 1145 additions and 8 deletions

123
src/routes/pictures.js Normal file
View File

@@ -0,0 +1,123 @@
const router = require('express').Router();
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const { query } = require('../db');
const { uploadFile, deleteFile, keyFromUrl } = require('../s3');
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } });
const ALLOWED_STATUSES = ['uploaded', 'published', 'blocked'];
const ALLOWED_BLOCKED_REASONS = ['regenerate', 'not_to_use'];
// GET /api/pictures
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 status = $3` : '';
if (status) params.push(status);
const result = await query(
`SELECT * FROM pictures ${where} ORDER BY created_at DESC LIMIT $1 OFFSET $2`,
params
);
res.json(result.rows);
} catch (err) { next(err); }
});
// GET /api/pictures/:id
router.get('/:id', async (req, res, next) => {
try {
const result = await query('SELECT * FROM pictures WHERE id = $1', [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/pictures — neuen Eintrag anlegen
router.post('/', async (req, res, next) => {
try {
const {
generation_prompt, generation_timestamp, generation_duration_s,
blurhash, design
} = req.body;
const result = await query(
`INSERT INTO pictures (generation_prompt, generation_timestamp, generation_duration_s, blurhash, design)
VALUES ($1, $2, $3, $4, $5) RETURNING *`,
[generation_prompt || null, generation_timestamp || null,
generation_duration_s || null, blurhash || null, design || null]
);
res.status(201).json(result.rows[0]);
} catch (err) { next(err); }
});
// POST /api/pictures/:id/upload — Bild zu Hetzner hochladen
router.post('/:id/upload', upload.single('file'), async (req, res, next) => {
try {
const existing = await query('SELECT * FROM pictures WHERE id = $1', [req.params.id]);
if (!existing.rows.length) return res.status(404).json({ error: 'Not found' });
if (!req.file) return res.status(400).json({ error: 'No file provided' });
const ext = req.file.originalname.split('.').pop().toLowerCase();
const key = `pictures/${req.params.id}/${uuidv4()}.${ext}`;
const url = await uploadFile(key, req.file.buffer, req.file.mimetype);
// Altes Bild löschen falls vorhanden
const oldKey = keyFromUrl(existing.rows[0].picture_link);
if (oldKey) await deleteFile(oldKey).catch(() => {});
const result = await query(
'UPDATE pictures SET picture_link = $1 WHERE id = $2 RETURNING *',
[url, req.params.id]
);
res.json(result.rows[0]);
} catch (err) { next(err); }
});
// PATCH /api/pictures/:id — Felder aktualisieren
router.patch('/:id', async (req, res, next) => {
try {
const allowed = [
'status', 'blocked_reason', 'generation_prompt', 'generation_timestamp',
'generation_duration_s', 'published_timestamp', 'blocked_timestamp',
'blurhash', 'picture_link', 'design'
];
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 && !ALLOWED_STATUSES.includes(req.body.status))
return res.status(400).json({ error: `status must be one of: ${ALLOWED_STATUSES.join(', ')}` });
if (req.body.blocked_reason && !ALLOWED_BLOCKED_REASONS.includes(req.body.blocked_reason))
return res.status(400).json({ error: `blocked_reason must be one of: ${ALLOWED_BLOCKED_REASONS.join(', ')}` });
// Auto-timestamps bei Statuswechsel
if (req.body.status === 'published' && !req.body.published_timestamp)
fields.push('published_timestamp'), req.body.published_timestamp = new Date().toISOString();
if (req.body.status === 'blocked' && !req.body.blocked_timestamp)
fields.push('blocked_timestamp'), req.body.blocked_timestamp = 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 pictures 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/pictures/:id — Eintrag + Hetzner-Datei löschen
router.delete('/:id', async (req, res, next) => {
try {
const existing = await query('SELECT picture_link FROM pictures WHERE id = $1', [req.params.id]);
if (!existing.rows.length) return res.status(404).json({ error: 'Not found' });
const key = keyFromUrl(existing.rows[0].picture_link);
if (key) await deleteFile(key).catch(() => {});
await query('DELETE FROM pictures WHERE id = $1', [req.params.id]);
res.status(204).end();
} catch (err) { next(err); }
});
module.exports = router;