22 lines
656 B
TypeScript
22 lines
656 B
TypeScript
import { ServiceError } from "./service-error";
|
|
|
|
export const jsonBodyLimit = 2 * 1024 * 1024;
|
|
|
|
export async function jsonBody(request: Pick<Request, "body">) {
|
|
const reader = request.body?.getReader();
|
|
if (!reader) throw new ServiceError("JSON request required", 400);
|
|
const chunks: Uint8Array[] = [];
|
|
let size = 0;
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
size += value.byteLength;
|
|
if (size > jsonBodyLimit) {
|
|
await reader.cancel();
|
|
throw new ServiceError("Request too large", 413);
|
|
}
|
|
chunks.push(value);
|
|
}
|
|
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
}
|