24 lines
818 B
TypeScript
24 lines
818 B
TypeScript
import type { NextRequest } from "next/server";
|
|
import { CONTENT_LIMITS } from "@/lib/validation/contentSchemas";
|
|
|
|
export class RequestTooLargeError extends Error {}
|
|
|
|
export async function readLimitedJson(
|
|
request: NextRequest,
|
|
maximumBytes = CONTENT_LIMITS.requestBytes
|
|
): Promise<unknown> {
|
|
const declaredLength = Number(request.headers.get("content-length"));
|
|
if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
|
|
throw new RequestTooLargeError(`Request body must not exceed ${maximumBytes} bytes`);
|
|
}
|
|
|
|
const body = await request.text();
|
|
if (new TextEncoder().encode(body).byteLength > maximumBytes) {
|
|
throw new RequestTooLargeError(`Request body must not exceed ${maximumBytes} bytes`);
|
|
}
|
|
try {
|
|
return JSON.parse(body) as unknown;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|