| 9 | import type { IncomingMessage, ServerResponse } from "node:http"; |
| 10 | |
| 11 | export async function readBody( |
| 12 | req: IncomingMessage, |
| 13 | maxBytes: number, |
| 14 | ): Promise<Buffer> { |
| 15 | if (req.method === "GET" || req.method === "HEAD") return Buffer.alloc(0); |
| 16 | const chunks: Buffer[] = []; |
| 17 | let total = 0; |
| 18 | for await (const chunk of req) { |
| 19 | const buf: Buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 20 | total += buf.length; |
| 21 | if (total > maxBytes) { |
| 22 | throw new Error(`body exceeds max size (${maxBytes} bytes)`); |
| 23 | } |
| 24 | chunks.push(buf); |
| 25 | } |
| 26 | return Buffer.concat(chunks); |
| 27 | } |
| 28 | |
| 29 | export function parseJsonBody<T = unknown>(body: Buffer): T { |
| 30 | if (body.length === 0) return {} as T; |