Files
bunext/dist/functions/server/handle-routes.js
T

105 lines
3.6 KiB
JavaScript

import grabRouteParams from "../../utils/grab-route-params";
import grabConstants from "../../utils/grab-constants";
import grabRouter from "../../utils/grab-router";
import isDevelopment from "../../utils/is-development";
import _ from "lodash";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import grabRelativePath from "../../utils/grab-relative-path";
const { ROOT_DIR } = grabDirNames();
export default async function ({ req }) {
const url = new URL(req.url);
const is_dev = isDevelopment();
const { MBInBytes, ServerDefaultRequestBodyLimitBytes } = grabConstants();
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Route ${url.pathname} not found`;
return Response.json({
success: false,
msg: errMsg,
}, {
status: 404,
headers: {
"Content-Type": "application/json",
},
});
}
const routeParams = await grabRouteParams({
req,
query: match.query,
});
let module;
const now = Date.now();
const relative_match_path = grabRelativePath(match.filePath);
if (is_dev &&
global.BUNEXT_SSR_BUNDLER_CTX_MAP?.[relative_match_path]?.path) {
const target_import = path.join(ROOT_DIR, global.BUNEXT_SSR_BUNDLER_CTX_MAP[relative_match_path].path);
module = await import(`${target_import}?t=${now}`);
}
else {
const import_path = is_dev
? `${match.filePath}?t=${now}`
: match.filePath;
module = await import(import_path);
}
const config = module.config;
const maxBodyBytes = config?.max_request_body_mb
? config.max_request_body_mb * MBInBytes
: ServerDefaultRequestBodyLimitBytes;
const contentLength = req.headers.get("content-length");
if (contentLength) {
const size = parseInt(contentLength, 10);
if (size > maxBodyBytes) {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, {
status: 413,
headers: {
"Content-Type": "application/json",
},
});
}
}
else if (req.method !== "GET" && req.method !== "HEAD") {
const body = await req.arrayBuffer();
if (body.byteLength > maxBodyBytes) {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, {
status: 413,
headers: {
"Content-Type": "application/json",
},
});
}
routeParams.body = JSON.parse(new TextDecoder().decode(body) || "{}");
}
const target_module = (module["default"] ||
module["handler"]);
const res = await target_module?.({
...routeParams,
});
if (res instanceof Response) {
if (is_dev) {
res.headers.set("Cache-Control", "no-cache, no-store, must-revalidate");
}
return res;
}
if (res) {
let final_res = Response.json(_.omit(res, [
"bunext_api_route_res_options",
"bunext_api_route_res_transform_fn",
]), {
...(res.bunext_api_route_res_options || undefined),
});
if (res.bunext_api_route_res_transform_fn) {
final_res = await res.bunext_api_route_res_transform_fn(final_res);
}
return final_res;
}
return Response.json({ err: `Route handler error` });
}