import express from 'express'; import { ObjectId } from 'mongodb'; import { getDB } from '../db.js'; import { upload } from '../middleware/upload.js'; import fs from 'fs'; import path from 'path'; const router = express.Router(); // Bild hochladen router.post('/:rezeptId', upload.single('bild'), async (req, res) => { try { if (!req.file) { return res.status(400).json({ error: 'Keine Datei hochgeladen' }); } const db = getDB(); const rezeptId = new ObjectId(req.params.rezeptId); const imageDoc = { rezeptId, dateiPfad: req.file.path.replace(/\\/g, '/'), dateiName: req.file.filename, hochgeladenAm: new Date() }; const result = await db.collection('images').insertOne(imageDoc); res.status(201).json({ _id: result.insertedId, ...imageDoc }); } catch (error) { res.status(500).json({ error: error.message }); } }); // Bild löschen router.delete('/:bildId', async (req, res) => { try { const db = getDB(); const bildId = new ObjectId(req.params.bildId); const image = await db.collection('images').findOne({ _id: bildId }); if (!image) { return res.status(404).json({ error: 'Bild nicht gefunden' }); } // Datei löschen if (fs.existsSync(image.dateiPfad)) { fs.unlinkSync(image.dateiPfad); } await db.collection('images').deleteOne({ _id: bildId }); res.json({ message: 'Bild gelöscht' }); } catch (error) { res.status(500).json({ error: error.message }); } }); // Bilder eines Rezepts abrufen router.get('/recipe/:rezeptId', async (req, res) => { try { const db = getDB(); const images = await db.collection('images') .find({ rezeptId: new ObjectId(req.params.rezeptId) }) .sort({ _id: 1 }) .toArray(); res.json(images); } catch (error) { res.status(500).json({ error: error.message }); } }); export default router;