MCPcopy
hub / github.com/browserless/browserless / readRequestBody

Function readRequestBody

src/utils.ts:254–303  ·  view source on GitHub ↗
(
  req: Request,
  maxSize: number = 10485760,
)

Source from the content-addressed store, hash-verified

252
253// NOTE, if proxying request elsewhere, you must re-stream the body again
254export const readRequestBody = async (
255 req: Request,
256 maxSize: number = 10485760,
257): Promise<string> => {
258 return new Promise((resolve, reject) => {
259 const body: Uint8Array[] = [];
260 let hasResolved = false;
261 let totalSize = 0;
262
263 const resolveOnce = (results: string) => {
264 if (hasResolved) {
265 return;
266 }
267 hasResolved = true;
268 resolve(results);
269 };
270
271 const rejectOnce = (error: Error) => {
272 if (hasResolved) {
273 return;
274 }
275 hasResolved = true;
276 reject(error);
277 };
278
279 req
280 .on('data', (chunk) => {
281 totalSize += chunk.length;
282 if (totalSize > maxSize) {
283 rejectOnce(
284 new BadRequest(
285 `Request payload size (${totalSize} bytes) exceeds maximum allowed size of ${maxSize} bytes`,
286 ),
287 );
288 return;
289 }
290 body.push(chunk);
291 })
292 .on('end', () => {
293 const final = Buffer.concat(body).toString();
294 resolveOnce(final);
295 })
296 .on('aborted', () => {
297 resolveOnce('');
298 })
299 .on('error', (error) => {
300 rejectOnce(error);
301 });
302 });
303};
304
305export const safeParse = (maybeJson: string): unknown | null => {
306 try {

Callers 1

readBodyFunction · 0.85

Calls 2

rejectOnceFunction · 0.85
resolveOnceFunction · 0.85

Tested by

no test coverage detected