Files
fiddle/server.js

225 lines
7.7 KiB
JavaScript

import express from 'express';
import { nanoid } from 'nanoid';
import db, { stmts, setFiddleTags, snapshotVersion } from './db.js';
const app = express();
app.use(express.json({ limit: '2mb' }));
// HTML routes must be defined before static middleware (which would serve index.html for /)
app.get('/', (_req, res) => {
res.sendFile('browse.html', { root: 'public' });
});
app.get('/new', (_req, res) => {
res.sendFile('index.html', { root: 'public' });
});
app.get('/embed/:id', (_req, res) => {
res.sendFile('embed.html', { root: 'public' });
});
app.get('/f/:id', (_req, res) => {
res.sendFile('index.html', { root: 'public' });
});
app.use(express.static('public', { index: false }));
// 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', listed = 1, options = '{}', tags = [] } = req.body;
try {
stmts.insert.run({ id, title, html, css, css_type, js, js_type, listed: listed ? 1 : 0, options });
if (tags.length) setFiddleTags(id, tags);
const fiddleTags = stmts.getTagsForFiddle.all(id);
res.json({ id, title, html, css, css_type, js, js_type, listed, options, tags: fiddleTags });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// API: List/search fiddles
app.get('/api/fiddles', (req, res) => {
const { q = '', js_type = '', tag = '', page = '1', limit = '20', sort = 'updated' } = req.query;
const pageNum = Math.max(1, parseInt(page, 10) || 1);
const limitNum = Math.min(100, Math.max(1, parseInt(limit, 10) || 20));
const offset = (pageNum - 1) * limitNum;
let where = 'WHERE f.listed = 1';
const params = {};
if (q) {
where += ' AND f.title LIKE @q';
params.q = `%${q}%`;
}
if (js_type) {
where += ' AND f.js_type = @js_type';
params.js_type = js_type;
}
if (tag) {
where += ' AND EXISTS (SELECT 1 FROM fiddle_tags ft2 JOIN tags t2 ON t2.id = ft2.tag_id WHERE ft2.fiddle_id = f.id AND t2.name = @tag COLLATE NOCASE)';
params.tag = tag;
}
const orderBy = sort === 'created' ? 'f.created_at DESC' : 'f.updated_at DESC';
try {
const countRow = db.prepare(`SELECT COUNT(*) as total FROM fiddles f ${where}`).get(params);
const fiddles = db.prepare(`
SELECT f.id, f.title, f.css_type, f.js_type, f.created_at, f.updated_at, f.screenshot,
SUBSTR(f.html, 1, 200) as html_preview, SUBSTR(f.js, 1, 200) as js_preview
FROM fiddles f ${where}
ORDER BY ${orderBy}
LIMIT @limit OFFSET @offset
`).all({ ...params, limit: limitNum, offset });
// Attach tags to each fiddle
for (const f of fiddles) {
f.tags = stmts.getTagsForFiddle.all(f.id);
}
res.json({ fiddles, total: countRow.total, page: pageNum, limit: limitNum });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// 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' });
fiddle.tags = stmts.getTagsForFiddle.all(fiddle.id);
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' });
// Snapshot current state as a version before overwriting
snapshotVersion(req.params.id);
const {
title = existing.title,
html = existing.html,
css = existing.css,
css_type = existing.css_type,
js = existing.js,
js_type = existing.js_type || 'javascript',
listed = existing.listed,
options = existing.options || '{}',
screenshot,
tags,
} = req.body;
stmts.update.run({ id: req.params.id, title, html, css, css_type, js, js_type, listed: listed ? 1 : 0, options });
if (screenshot !== undefined) stmts.updateScreenshot.run(screenshot, req.params.id);
if (Array.isArray(tags)) setFiddleTags(req.params.id, tags);
const fiddleTags = stmts.getTagsForFiddle.all(req.params.id);
res.json({ id: req.params.id, title, html, css, css_type, js, js_type, listed, options, tags: fiddleTags });
});
// API: List tags
app.get('/api/tags', (_req, res) => {
res.json({ tags: stmts.listTags.all() });
});
// ===================== Version History API =====================
app.get('/api/fiddles/:id/versions', (req, res) => {
const fiddle = stmts.get.get(req.params.id);
if (!fiddle) return res.status(404).json({ error: 'Not found' });
const versions = stmts.listVersions.all(req.params.id);
res.json({ versions });
});
app.get('/api/fiddles/:id/versions/:ver', (req, res) => {
const ver = parseInt(req.params.ver, 10);
const version = stmts.getVersion.get(req.params.id, ver);
if (!version) return res.status(404).json({ error: 'Version not found' });
res.json(version);
});
app.post('/api/fiddles/:id/revert/:ver', (req, res) => {
const existing = stmts.get.get(req.params.id);
if (!existing) return res.status(404).json({ error: 'Not found' });
const ver = parseInt(req.params.ver, 10);
const version = stmts.getVersion.get(req.params.id, ver);
if (!version) return res.status(404).json({ error: 'Version not found' });
// Snapshot current state before reverting
snapshotVersion(req.params.id);
stmts.update.run({
id: req.params.id,
title: existing.title,
html: version.html,
css: version.css,
css_type: version.css_type,
js: version.js,
js_type: version.js_type,
listed: existing.listed,
options: version.options || existing.options || '{}',
});
const updated = stmts.get.get(req.params.id);
updated.tags = stmts.getTagsForFiddle.all(req.params.id);
res.json(updated);
});
// ===================== Collections API =====================
app.post('/api/collections', (req, res) => {
const id = nanoid(10);
const { name = 'Untitled Collection', description = '' } = req.body;
try {
stmts.insertCollection.run({ id, name, description });
res.json({ id, name, description, fiddle_count: 0 });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.get('/api/collections', (_req, res) => {
res.json({ collections: stmts.listCollections.all() });
});
app.get('/api/collections/:id', (req, res) => {
const col = stmts.getCollection.get(req.params.id);
if (!col) return res.status(404).json({ error: 'Not found' });
const fiddles = stmts.getCollectionFiddles.all(req.params.id);
for (const f of fiddles) f.tags = stmts.getTagsForFiddle.all(f.id);
res.json({ ...col, fiddles });
});
app.put('/api/collections/:id', (req, res) => {
const col = stmts.getCollection.get(req.params.id);
if (!col) return res.status(404).json({ error: 'Not found' });
const { name = col.name, description = col.description } = req.body;
stmts.updateCollection.run({ id: req.params.id, name, description });
res.json({ id: req.params.id, name, description });
});
app.delete('/api/collections/:id', (req, res) => {
const col = stmts.getCollection.get(req.params.id);
if (!col) return res.status(404).json({ error: 'Not found' });
stmts.deleteCollection.run(req.params.id);
res.json({ ok: true });
});
app.post('/api/collections/:id/fiddles', (req, res) => {
const col = stmts.getCollection.get(req.params.id);
if (!col) return res.status(404).json({ error: 'Collection not found' });
const { fiddle_id } = req.body;
if (!fiddle_id) return res.status(400).json({ error: 'fiddle_id required' });
stmts.addFiddleToCollection.run({ collection_id: req.params.id, fiddle_id });
res.json({ ok: true });
});
app.delete('/api/collections/:id/fiddles/:fid', (req, res) => {
stmts.removeFiddleFromCollection.run(req.params.id, req.params.fid);
res.json({ ok: true });
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Fiddle server running on http://localhost:${port}`));