| 9 | const MAX_JSON_BODY_BYTES = 1024 * 1024; |
| 10 | |
| 11 | export async function readJsonBody(req: IncomingMessage): Promise<unknown> { |
| 12 | let total = 0; |
| 13 | const chunks: Buffer[] = []; |
| 14 | for await (const chunk of req) { |
| 15 | const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 16 | total += buf.length; |
| 17 | if (total > MAX_JSON_BODY_BYTES) { |
| 18 | throw new Error(`Request body exceeds ${MAX_JSON_BODY_BYTES} bytes`); |
| 19 | } |
| 20 | chunks.push(buf); |
| 21 | } |
| 22 | const text = Buffer.concat(chunks).toString("utf8"); |
| 23 | if (text.length === 0) return {}; |
| 24 | return JSON.parse(text); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Reads and validates a JSON request body at the route boundary. Returns the parsed |