42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import { Router, type Request, type Response } from 'express';
|
|
import { pipeline } from 'node:stream/promises';
|
|
import { getAllNotes, streamAllNotes } from '../db/notes.dao.js';
|
|
import { clusterNotes } from '../services/clustering.service.js';
|
|
import { jsonArray } from '../lib/streams.js';
|
|
|
|
const router = Router();
|
|
|
|
router.get('/', async (_req: Request, res: Response) => {
|
|
try {
|
|
const rows = await streamAllNotes();
|
|
res.type('application/json');
|
|
await pipeline(rows, jsonArray(), res);
|
|
} catch (err) {
|
|
console.error(`Error loading notes: ${err}`);
|
|
if (res.headersSent) {
|
|
res.destroy(err as Error);
|
|
return;
|
|
}
|
|
res.status(500).json({ error: 'Failed to load notes' });
|
|
}
|
|
});
|
|
|
|
router.post('/cluster', async (_req: Request, res: Response) => {
|
|
const controller = new AbortController();
|
|
res.on('close', () => {
|
|
if (!res.writableEnded) controller.abort();
|
|
});
|
|
|
|
try {
|
|
const notes = await getAllNotes();
|
|
const result = await clusterNotes(notes, { signal: controller.signal });
|
|
res.json(result);
|
|
} catch (err) {
|
|
if (controller.signal.aborted) return;
|
|
console.error(`Clustering failed: ${err}`);
|
|
res.status(500).json({ error: 'Clustering failed' });
|
|
}
|
|
});
|
|
|
|
export default router;
|