59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
|
|
import { Router } from 'express';
|
||
|
|
import { requireToken } from './auth.js';
|
||
|
|
import { upsertArticle, listArticles, getArticle, updateArticle, deleteArticle } from './db.js';
|
||
|
|
|
||
|
|
const router = Router();
|
||
|
|
|
||
|
|
// POST /api/capture — what the extension hits on "Send to stash".
|
||
|
|
router.post('/capture', requireToken, (req, res) => {
|
||
|
|
const { url, title, content_html, content_text, author, published_at } = req.body ?? {};
|
||
|
|
if (!url || !title || !content_html || !content_text) {
|
||
|
|
res.status(400).json({ error: 'url, title, content_html, content_text are required' });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const article = upsertArticle({ url, title, content_html, content_text, author, published_at });
|
||
|
|
res.json(article);
|
||
|
|
} catch (e: any) {
|
||
|
|
res.status(500).json({ error: e.message });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
// GET /api/articles?unread=true&q=<search>&limit=50
|
||
|
|
router.get('/articles', requireToken, (req, res) => {
|
||
|
|
const unread = req.query.unread === 'true';
|
||
|
|
const q = typeof req.query.q === 'string' && req.query.q.trim() ? req.query.q.trim() : undefined;
|
||
|
|
const limit = Math.min(Number(req.query.limit) || 50, 500);
|
||
|
|
try {
|
||
|
|
res.json(listArticles({ unread, q, limit }));
|
||
|
|
} catch (e: any) {
|
||
|
|
res.status(500).json({ error: e.message });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
router.get('/articles/:id', requireToken, (req, res) => {
|
||
|
|
const article = getArticle(Number(req.params.id));
|
||
|
|
if (!article) { res.status(404).json({ error: 'not found' }); return; }
|
||
|
|
res.json(article);
|
||
|
|
});
|
||
|
|
|
||
|
|
router.patch('/articles/:id', requireToken, (req, res) => {
|
||
|
|
const id = Number(req.params.id);
|
||
|
|
const { read, tags } = req.body ?? {};
|
||
|
|
const patch: { read_at?: string | null; tags?: string } = {};
|
||
|
|
if (read === true) patch.read_at = new Date().toISOString();
|
||
|
|
if (read === false) patch.read_at = null;
|
||
|
|
if (typeof tags === 'string') patch.tags = tags;
|
||
|
|
const article = updateArticle(id, patch);
|
||
|
|
if (!article) { res.status(404).json({ error: 'not found' }); return; }
|
||
|
|
res.json(article);
|
||
|
|
});
|
||
|
|
|
||
|
|
router.delete('/articles/:id', requireToken, (req, res) => {
|
||
|
|
const ok = deleteArticle(Number(req.params.id));
|
||
|
|
if (!ok) { res.status(404).json({ error: 'not found' }); return; }
|
||
|
|
res.json({ ok: true });
|
||
|
|
});
|
||
|
|
|
||
|
|
export default router;
|