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:
928
package-lock.json
generated
928
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@@ -8,11 +8,15 @@
|
|||||||
"dev": "nodemon src/index.js"
|
"dev": "nodemon src/index.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.19.2",
|
"@aws-sdk/client-s3": "^3.1050.0",
|
||||||
"pg": "^8.11.3",
|
"@aws-sdk/lib-storage": "^3.1050.0",
|
||||||
"dotenv": "^16.4.5",
|
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"express-validator": "^7.1.0"
|
"dotenv": "^16.4.5",
|
||||||
|
"express": "^4.19.2",
|
||||||
|
"express-validator": "^7.1.0",
|
||||||
|
"multer": "^2.1.1",
|
||||||
|
"pg": "^8.11.3",
|
||||||
|
"uuid": "^14.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"nodemon": "^3.1.0"
|
"nodemon": "^3.1.0"
|
||||||
|
|||||||
40
src/db-migrate.js
Normal file
40
src/db-migrate.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
const { query } = require('./db');
|
||||||
|
|
||||||
|
async function migrate() {
|
||||||
|
await query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS pictures (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'uploaded'
|
||||||
|
CHECK (status IN ('uploaded', 'published', 'blocked')),
|
||||||
|
blocked_reason VARCHAR(20) CHECK (blocked_reason IN ('regenerate', 'not_to_use')),
|
||||||
|
generation_prompt TEXT,
|
||||||
|
generation_timestamp TIMESTAMPTZ,
|
||||||
|
generation_duration_s NUMERIC(10,3),
|
||||||
|
published_timestamp TIMESTAMPTZ,
|
||||||
|
blocked_timestamp TIMESTAMPTZ,
|
||||||
|
blurhash TEXT,
|
||||||
|
picture_link TEXT,
|
||||||
|
design TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await query(`
|
||||||
|
CREATE OR REPLACE FUNCTION update_updated_at()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN NEW.updated_at = NOW(); RETURN NEW; END;
|
||||||
|
$$ LANGUAGE plpgsql
|
||||||
|
`);
|
||||||
|
|
||||||
|
await query(`
|
||||||
|
DROP TRIGGER IF EXISTS pictures_updated_at ON pictures;
|
||||||
|
CREATE TRIGGER pictures_updated_at
|
||||||
|
BEFORE UPDATE ON pictures
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION update_updated_at()
|
||||||
|
`);
|
||||||
|
|
||||||
|
console.log('Migration complete: pictures table ready');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = migrate;
|
||||||
@@ -3,6 +3,7 @@ const express = require('express');
|
|||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
const auth = require('./middleware/auth');
|
const auth = require('./middleware/auth');
|
||||||
const { pool } = require('./db');
|
const { pool } = require('./db');
|
||||||
|
const migrate = require('./db-migrate');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const PORT = process.env.PORT || 3000;
|
const PORT = process.env.PORT || 3000;
|
||||||
@@ -23,6 +24,7 @@ app.get('/health', async (req, res) => {
|
|||||||
|
|
||||||
// Routes — protected by Bearer token
|
// Routes — protected by Bearer token
|
||||||
app.use('/api', auth, require('./routes/index'));
|
app.use('/api', auth, require('./routes/index'));
|
||||||
|
app.use('/api/pictures', auth, require('./routes/pictures'));
|
||||||
|
|
||||||
// 404
|
// 404
|
||||||
app.use((req, res) => {
|
app.use((req, res) => {
|
||||||
@@ -35,6 +37,6 @@ app.use((err, req, res, next) => {
|
|||||||
res.status(500).json({ error: 'Internal server error' });
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
});
|
});
|
||||||
|
|
||||||
app.listen(PORT, '0.0.0.0', () => {
|
migrate()
|
||||||
console.log(`snakkimo-API running on port ${PORT}`);
|
.then(() => app.listen(PORT, '0.0.0.0', () => console.log(`snakkimo-API running on port ${PORT}`)))
|
||||||
});
|
.catch(err => { console.error('Migration failed:', err); process.exit(1); });
|
||||||
|
|||||||
123
src/routes/pictures.js
Normal file
123
src/routes/pictures.js
Normal 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;
|
||||||
42
src/s3.js
Normal file
42
src/s3.js
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
const { S3Client, DeleteObjectCommand } = require('@aws-sdk/client-s3');
|
||||||
|
const { Upload } = require('@aws-sdk/lib-storage');
|
||||||
|
|
||||||
|
const BUCKET = 'snakkimo';
|
||||||
|
const ENDPOINT = 'https://fsn1.your-objectstorage.com';
|
||||||
|
const PUBLIC_BASE = `https://${BUCKET}.fsn1.your-objectstorage.com`;
|
||||||
|
|
||||||
|
const client = new S3Client({
|
||||||
|
region: 'fsn1',
|
||||||
|
endpoint: ENDPOINT,
|
||||||
|
credentials: {
|
||||||
|
accessKeyId: process.env.S3_ACCESS_KEY,
|
||||||
|
secretAccessKey: process.env.S3_SECRET_KEY,
|
||||||
|
},
|
||||||
|
forcePathStyle: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
async function uploadFile(key, buffer, mimetype) {
|
||||||
|
const upload = new Upload({
|
||||||
|
client,
|
||||||
|
params: {
|
||||||
|
Bucket: BUCKET,
|
||||||
|
Key: key,
|
||||||
|
Body: buffer,
|
||||||
|
ContentType: mimetype,
|
||||||
|
ACL: 'public-read',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await upload.done();
|
||||||
|
return `${PUBLIC_BASE}/${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteFile(key) {
|
||||||
|
await client.send(new DeleteObjectCommand({ Bucket: BUCKET, Key: key }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function keyFromUrl(url) {
|
||||||
|
if (!url) return null;
|
||||||
|
return url.replace(`${PUBLIC_BASE}/`, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { uploadFile, deleteFile, keyFromUrl };
|
||||||
Reference in New Issue
Block a user