feature: sort imports to try to ensure parameter paths are less specific

This commit is contained in:
Andy Burke 2025-06-25 20:07:08 -07:00
parent c92ef0688b
commit 4f68a64a88
4 changed files with 72 additions and 10 deletions

View file

@ -53,6 +53,11 @@ export default async function handle_typescript(request: Request): Promise<Respo
const root_directory = path.resolve(Deno.cwd());
type import_record = {
route_path: string;
import_path: string;
};
const imports: import_record[] = [];
for await (
const entry of walk(root_directory, {
exts: ['.ts'],
@ -70,19 +75,33 @@ export default async function handle_typescript(request: Request): Promise<Respo
const import_path = new URL('file://' + entry.path, import.meta.url).toString();
try {
const module: ROUTE_HANDLER = await import(import_path) as ROUTE_HANDLER;
imports.push({
route_path,
import_path
});
}
}
const pattern = new URLPattern({ pathname: route_path });
// try to sort imports such that they're registered like:
// /permissions/test
// /echo/hi
// /echo/:input
//
// we want paths with parameters to sort later than paths without
const sorted_imports = imports.sort((lhs, rhs) => rhs.route_path.localeCompare(lhs.route_path));
for (const import_info of sorted_imports) {
try {
const module: ROUTE_HANDLER = await import(import_info.import_path) as ROUTE_HANDLER;
if (Deno.env.get('SERVERUS_TYPESCRIPT_IMPORT_LOGGING')) {
console.log(`imported: ${import_path}`);
}
const pattern = new URLPattern({ pathname: import_info.route_path });
routes.set(pattern, module);
} catch (error) {
console.error(`Error mounting module ${import_path} at ${route_path}\n\n${error}\n`);
if (Deno.env.get('SERVERUS_TYPESCRIPT_IMPORT_LOGGING')) {
console.log(`imported: ${import_info.import_path}`);
}
routes.set(pattern, module);
} catch (error) {
console.error(`Error mounting module ${import_info.import_path} at ${import_info.route_path}\n\n${error}\n`);
}
}