import _ from "lodash"; import deserializeQuery from "./deserialize-query"; import grabConstants from "./grab-constants"; import readRequestBody from "./read-request-body"; /** * Throws `RequestBodyTooLargeError` if the body exceeds `max_body_bytes`. */ export default async function grabRouteParams({ req: initial_req, query: passed_query, max_body_bytes, }) { const url = new URL(initial_req.url); const query = deserializeQuery(Object.fromEntries(url.searchParams)); const raw_body = await readRequestBody({ req: initial_req, max_bytes: max_body_bytes || grabConstants().ServerDefaultRequestBodyLimitBytes, }); // The original body stream is consumed above, so hand handlers a fresh // request over the buffered bytes. This keeps `req.text()`, // `req.formData()`, etc. usable (e.g. for webhook signatures/uploads). const req = raw_body ? new Request(initial_req.url, { method: initial_req.method, headers: initial_req.headers, body: raw_body, signal: initial_req.signal, }) : initial_req; const body = (() => { if (initial_req.method == "GET") return undefined; if (!raw_body) return {}; try { return JSON.parse(new TextDecoder().decode(raw_body) || "{}"); } catch (error) { return {}; } })(); const routeParams = { req, url, query: _.merge(query, passed_query), body, server: global.BUNEXT_SERVER, }; return routeParams; }