Add docs navigation and tighten API request security
This commit is contained in:
21
lib/json-body.ts
Normal file
21
lib/json-body.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
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"));
|
||||
}
|
||||
Reference in New Issue
Block a user