Files
kongruity/backend/routes/ingest.routes.ts

49 lines
1.4 KiB
TypeScript

import { Router, type Request, type Response } from 'express';
import { requireApiKey } from '../middleware/apiKey.js';
import { createNotes } from '../db/notes.dao.js';
import { isNoteInputArray } from '../config/normalizers.js';
import type { NoteInput } from '../types/domain.js';
const router = Router();
const MAX_BATCH = 5000;
type IngestBody = { notes: NoteInput[] };
const isIngestBody = (value: unknown): value is IngestBody => {
if (typeof value !== 'object' || value === null) return false;
const body = value as Record<string, unknown>;
return isNoteInputArray(body.notes);
};
router.post('/', requireApiKey, async (req: Request, res: Response) => {
try {
if (!isIngestBody(req.body)) {
res.status(400).json({
error: 'Body must be { notes: [{ id, text, author, ... }] }',
});
return;
}
const { notes } = req.body;
if (notes.length === 0) {
res.status(400).json({ error: 'notes must not be empty' });
return;
}
if (notes.length > MAX_BATCH) {
res.status(400).json({ error: `notes exceeds the ${MAX_BATCH} per-request limit` });
return;
}
const inserted = await createNotes(notes);
res.status(201).json({ inserted: inserted.length, notes: inserted });
} catch (err) {
console.error(`Ingest failed: ${err}`);
res.status(500).json({ error: 'Ingest failed' });
}
});
export default router;