mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-04 10:24:02 +00:00
37 lines
1001 B
JavaScript
37 lines
1001 B
JavaScript
|
|
/** Read a request body with a hard byte cap; throws { code:'BODY_TOO_LARGE' } past the cap. */
|
|
async function readRequestBodyCapped(req, maxBytes) {
|
|
const chunks = [];
|
|
let total = 0;
|
|
for await (const chunk of req) {
|
|
total += chunk.length;
|
|
if (total > maxBytes) {
|
|
const err = new Error('Request body too large');
|
|
err.code = 'BODY_TOO_LARGE';
|
|
throw err;
|
|
}
|
|
chunks.push(chunk);
|
|
}
|
|
return Buffer.concat(chunks);
|
|
}
|
|
|
|
function readRequestBody(req, maxBytes = 1024 * 1024) {
|
|
return new Promise((resolve, reject) => {
|
|
let total = 0;
|
|
const chunks = [];
|
|
req.on('data', (chunk) => {
|
|
total += chunk.length;
|
|
if (total > maxBytes) {
|
|
reject(new Error(`Request body exceeds ${maxBytes} bytes`));
|
|
req.destroy();
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
req.on('error', reject);
|
|
});
|
|
}
|
|
|
|
export { readRequestBodyCapped, readRequestBody };
|