feat: support lazily loading routes/handlers (#3131)
We can improve cold start times by only loading route modules when the particular pattern matches. This PR introduces the concept of lazy middlewares, routes and handlers to do that.
This commit is contained in:
+23
-2
@@ -5,6 +5,7 @@ import * as path from "@std/path";
|
||||
import { pathToPattern } from "../router.ts";
|
||||
import { CommandType } from "../commands.ts";
|
||||
import { sortRoutePaths } from "../fs_routes.ts";
|
||||
import type { RouteConfig } from "../types.ts";
|
||||
|
||||
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
|
||||
|
||||
@@ -18,7 +19,7 @@ export async function crawlRouteDir<State>(
|
||||
await walkDir(
|
||||
fs,
|
||||
routeDir,
|
||||
(entry) => {
|
||||
async (entry) => {
|
||||
// A `(_islands)` path segment is a local island folder.
|
||||
// Any route path segment wrapped in `(_...)` is ignored
|
||||
// during route collection.
|
||||
@@ -30,10 +31,12 @@ export async function crawlRouteDir<State>(
|
||||
return;
|
||||
}
|
||||
|
||||
let lazy = false;
|
||||
const relative = path.relative(routeDir, entry.path);
|
||||
const url = new URL(relative, "http://localhost/");
|
||||
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
|
||||
|
||||
let overrideConfig: RouteConfig | undefined;
|
||||
let pattern = "*";
|
||||
let routePattern = pattern;
|
||||
let type = CommandType.Route;
|
||||
@@ -71,9 +74,27 @@ export async function crawlRouteDir<State>(
|
||||
}
|
||||
|
||||
routePattern = pathToPattern(id.slice(1));
|
||||
|
||||
const code = await fs.readTextFile(entry.path);
|
||||
lazy = !code.includes("routeOverride");
|
||||
|
||||
// TODO: We could do an AST parse here to detect the
|
||||
// kind of handler that's used to get a more accurate
|
||||
// list of methods this route supports.
|
||||
overrideConfig = {
|
||||
methods: "ALL",
|
||||
};
|
||||
}
|
||||
|
||||
files.push({ id, filePath: entry.path, type, pattern, routePattern });
|
||||
files.push({
|
||||
id,
|
||||
filePath: entry.path,
|
||||
type,
|
||||
pattern,
|
||||
routePattern,
|
||||
lazy,
|
||||
overrideConfig,
|
||||
});
|
||||
},
|
||||
ignore,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user