const express = require('express'); const fs = require('fs').promises; const path = require('path'); const app = express(); const PORT = 3000; const RECIPES_DIR = path.join(__dirname, 'recipes'); app.use(express.json()); app.use(express.static('public')); // Ensure recipes directory exists async function ensureRecipesDir() { try { await fs.access(RECIPES_DIR); } catch { await fs.mkdir(RECIPES_DIR, { recursive: true }); } } // GET all recipes app.get('/api/recipes', async (req, res) => { try { await ensureRecipesDir(); const files = await fs.readdir(RECIPES_DIR); const recipes = []; for (const file of files) { if (file.endsWith('.json')) { const content = await fs.readFile(path.join(RECIPES_DIR, file), 'utf-8'); recipes.push(JSON.parse(content)); } } res.json(recipes); } catch (error) { res.status(500).json({ error: 'Failed to load recipes' }); } }); // GET single recipe by id app.get('/api/recipes/:id', async (req, res) => { try { const filePath = path.join(RECIPES_DIR, `${req.params.id}.json`); const content = await fs.readFile(filePath, 'utf-8'); res.json(JSON.parse(content)); } catch (error) { res.status(404).json({ error: 'Recipe not found' }); } }); // POST new recipe app.post('/api/recipes', async (req, res) => { try { await ensureRecipesDir(); const recipe = req.body; // Generate ID if not provided if (!recipe.id) { recipe.id = Date.now().toString(36) + Math.random().toString(36).substr(2); } recipe.createdAt = recipe.createdAt || new Date().toISOString(); recipe.updatedAt = new Date().toISOString(); const filePath = path.join(RECIPES_DIR, `${recipe.id}.json`); await fs.writeFile(filePath, JSON.stringify(recipe, null, 2)); res.status(201).json(recipe); } catch (error) { res.status(500).json({ error: 'Failed to save recipe' }); } }); // PUT update recipe app.put('/api/recipes/:id', async (req, res) => { try { const recipe = req.body; recipe.id = req.params.id; recipe.updatedAt = new Date().toISOString(); const filePath = path.join(RECIPES_DIR, `${recipe.id}.json`); await fs.writeFile(filePath, JSON.stringify(recipe, null, 2)); res.json(recipe); } catch (error) { res.status(500).json({ error: 'Failed to update recipe' }); } }); // DELETE recipe app.delete('/api/recipes/:id', async (req, res) => { try { const filePath = path.join(RECIPES_DIR, `${req.params.id}.json`); await fs.unlink(filePath); res.json({ success: true }); } catch (error) { res.status(500).json({ error: 'Failed to delete recipe' }); } }); app.listen(PORT, () => { console.log(`🍳 Cookbook server running at http://localhost:${PORT}`); });