28 lines
892 B
TypeScript
28 lines
892 B
TypeScript
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { BlobTooLargeError } from "./blobStore.ts";
|
|
|
|
export function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
|
const payload = JSON.stringify(body);
|
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
res.end(payload);
|
|
}
|
|
|
|
export async function readLimitedBody(req: IncomingMessage, limitBytes: number): Promise<Buffer> {
|
|
const declaredLength = Number(req.headers["content-length"] ?? 0);
|
|
if (declaredLength > limitBytes) {
|
|
throw new BlobTooLargeError(limitBytes);
|
|
}
|
|
|
|
const chunks: Buffer[] = [];
|
|
let total = 0;
|
|
for await (const chunk of req) {
|
|
total += (chunk as Buffer).length;
|
|
if (total > limitBytes) {
|
|
req.destroy();
|
|
throw new BlobTooLargeError(limitBytes);
|
|
}
|
|
chunks.push(chunk as Buffer);
|
|
}
|
|
return Buffer.concat(chunks, total);
|
|
}
|