25 lines
711 B
TypeScript
25 lines
711 B
TypeScript
export const BILL_BODY_LIMIT = 64 * 1024;
|
|
|
|
export async function readLimited(request: Request, max: number): Promise<string | null> {
|
|
const declared = request.headers.get("content-length");
|
|
if (declared && Number(declared) > max) return null;
|
|
const reader = request.body?.getReader();
|
|
if (!reader) return "";
|
|
let total = 0;
|
|
const decoder = new TextDecoder();
|
|
let text = "";
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
if (!value) continue;
|
|
total += value.byteLength;
|
|
if (total > max) {
|
|
await reader.cancel();
|
|
return null;
|
|
}
|
|
text += decoder.decode(value, { stream: true });
|
|
}
|
|
text += decoder.decode();
|
|
return text;
|
|
}
|