import express from 'express'; import { nanoid } from 'nanoid'; import { stmts } from './db.js'; const app = express(); app.use(express.json()); app.use(express.static('public')); // API: Create fiddle app.post('/api/fiddles', (req, res) => { const id = nanoid(10); const { title = 'Untitled', html = '', css = '', css_type = 'css', js = '', js_type = 'javascript' } = req.body; try { stmts.insert.run({ id, title, html, css, css_type, js, js_type }); res.json({ id, title, html, css, css_type, js, js_type }); } catch (e) { res.status(500).json({ error: e.message }); } }); // API: List recent fiddles app.get('/api/fiddles', (_req, res) => { res.json(stmts.list.all()); }); // API: Get fiddle app.get('/api/fiddles/:id', (req, res) => { const fiddle = stmts.get.get(req.params.id); if (!fiddle) return res.status(404).json({ error: 'Not found' }); res.json(fiddle); }); // API: Update fiddle app.put('/api/fiddles/:id', (req, res) => { const existing = stmts.get.get(req.params.id); if (!existing) return res.status(404).json({ error: 'Not found' }); const { title = existing.title, html = existing.html, css = existing.css, css_type = existing.css_type, js = existing.js, js_type = existing.js_type || 'javascript' } = req.body; stmts.update.run({ id: req.params.id, title, html, css, css_type, js, js_type }); res.json({ id: req.params.id, title, html, css, css_type, js, js_type }); }); // SPA route: serve index.html for /f/:id app.get('/f/:id', (_req, res) => { res.sendFile('index.html', { root: 'public' }); }); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Fiddle server running on http://localhost:${port}`));