Files
ai-taxonomy-literature-anal…/lib/api.ts
T
2026-10-30 20:07:06 +08:00

39 lines
1.7 KiB
TypeScript

import type { NextApiRequest, NextApiResponse } from 'next';
import { COOKIE, validSession } from './editor-session';
export class HttpError extends Error {
constructor(public status: number, message: string) { super(message); }
}
type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
type Handler = (req: NextApiRequest) => Promise<unknown>;
/** Dispatch by HTTP method; a handler returns the JSON to send, or throws HttpError. */
export function route(handlers: Partial<Record<Method, Handler>>) {
return async (req: NextApiRequest, res: NextApiResponse) => {
res.setHeader('Cache-Control', 'private, no-store');
if (!await validSession(req.cookies[COOKIE])) return res.status(401).json({ error: 'Editor authentication required' });
if (req.method !== 'GET' && (!process.env.EDITOR_ORIGIN || req.headers.origin !== process.env.EDITOR_ORIGIN)) return res.status(403).json({ error: 'Invalid origin' });
const h = handlers[req.method as Method];
if (!h) {
res.setHeader('Allow', Object.keys(handlers).join(', '));
return res.status(405).json({ error: `method ${req.method} not allowed` });
}
try {
res.status(200).json((await h(req)) ?? { ok: true });
} catch (e) {
if (e instanceof HttpError) return res.status(e.status).json({ error: e.message });
console.error(e);
res.status(500).json({ error: `internal error: ${(e as Error).message}` });
}
};
}
export function bodyObject(req: NextApiRequest): Record<string, any> {
const b = req.body;
if (!b || typeof b !== 'object' || Array.isArray(b)) throw new HttpError(400, 'request body must be a JSON object (send Content-Type: application/json)');
return b;
}
export const bigBody = { api: { bodyParser: { sizeLimit: '8mb' } } };