import type { NextApiRequest, NextApiResponse } from 'next'; export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } } type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'; type Handler = (req: NextApiRequest) => Promise; /** Dispatch by HTTP method; a handler returns the JSON to send, or throws HttpError. */ export function route(handlers: Partial>) { return async (req: NextApiRequest, res: NextApiResponse) => { 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 { 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' } } };