Files
studyos/server/routes/notes.js
2026-06-08 16:53:18 -03:00

105 lines
2.9 KiB
JavaScript

const express = require('express');
const db = require('../db');
const router = express.Router();
// GET /api/notes — list all
router.get('/', (req, res) => {
try {
const rows = db.prepare('SELECT * FROM notes ORDER BY updated_at DESC').all();
res.json(rows);
} catch (err) {
console.error('[notes] list error:', err.message);
res.status(500).json({ error: err.message });
}
});
// POST /api/notes — create
router.post('/', (req, res) => {
const { title, content_markdown, tags = [] } = req.body;
if (!title) {
return res.status(400).json({ error: 'title is required' });
}
let tagsJson;
try {
tagsJson = JSON.stringify(Array.isArray(tags) ? tags : []);
} catch {
return res.status(400).json({ error: 'tags must be a valid array' });
}
try {
const info = db.prepare(`
INSERT INTO notes (title, content_markdown, tags)
VALUES (?, ?, ?)
`).run(title, content_markdown || '', tagsJson);
const row = db.prepare('SELECT * FROM notes WHERE id = ?').get(info.lastInsertRowid);
res.status(201).json(row);
} catch (err) {
console.error('[notes] create error:', err.message);
res.status(500).json({ error: err.message });
}
});
// PUT /api/notes/:id — update (updated_at auto-set)
router.put('/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid note id' });
}
const { title, content_markdown, tags } = req.body;
let tagsJson = undefined;
if (tags !== undefined) {
try {
tagsJson = JSON.stringify(Array.isArray(tags) ? tags : []);
} catch {
return res.status(400).json({ error: 'tags must be a valid array' });
}
}
try {
const existing = db.prepare('SELECT * FROM notes WHERE id = ?').get(id);
if (!existing) {
return res.status(404).json({ error: 'Note not found' });
}
db.prepare(`
UPDATE notes SET
title = COALESCE(?, title),
content_markdown = COALESCE(?, content_markdown),
tags = COALESCE(?, tags),
updated_at = datetime('now')
WHERE id = ?
`).run(title ?? null, content_markdown ?? null, tagsJson ?? null, id);
const row = db.prepare('SELECT * FROM notes WHERE id = ?').get(id);
res.json(row);
} catch (err) {
console.error('[notes] update error:', err.message);
res.status(500).json({ error: err.message });
}
});
// DELETE /api/notes/:id
router.delete('/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid note id' });
}
try {
const info = db.prepare('DELETE FROM notes WHERE id = ?').run(id);
if (info.changes === 0) {
return res.status(404).json({ error: 'Note not found' });
}
res.json({ deleted: true });
} catch (err) {
console.error('[notes] delete error:', err.message);
res.status(500).json({ error: err.message });
}
});
module.exports = router;