From d917b697533d1e5a5ec9f82c58f1cb9b8d409b0d Mon Sep 17 00:00:00 2001 From: Andy Burke Date: Wed, 25 Jun 2025 20:46:09 -0700 Subject: [PATCH] fix: sort routes into route records and lazily import --- deno.json | 2 +- handlers/typescript.ts | 58 +++++++++++----------- tests/03_get_typescript_route.test.ts | 2 +- tests/04_test_overriding_handlers.test.ts | 2 +- tests/07_test_route_sorting.test.ts | 6 +-- tests/www/{ => api}/echo/___input/index.ts | 0 tests/www/{ => api}/echo/hi/index.ts | 0 tests/www/{ => api}/echo/index.ts | 0 8 files changed, 33 insertions(+), 37 deletions(-) rename tests/www/{ => api}/echo/___input/index.ts (100%) rename tests/www/{ => api}/echo/hi/index.ts (100%) rename tests/www/{ => api}/echo/index.ts (100%) diff --git a/deno.json b/deno.json index cf6a7d0..276878e 100644 --- a/deno.json +++ b/deno.json @@ -1,7 +1,7 @@ { "name": "@andyburke/serverus", "description": "A flexible HTTP server for mixed content. Throw static files, markdown, Typescript and (hopefully, eventually) more into a directory and serverus can serve it up a bit more like old-school CGI.", - "version": "0.5.0", + "version": "0.6.0", "license": "MIT", "exports": { ".": "./serverus.ts", diff --git a/handlers/typescript.ts b/handlers/typescript.ts index 4efb38a..009a401 100644 --- a/handlers/typescript.ts +++ b/handlers/typescript.ts @@ -32,7 +32,13 @@ export interface ROUTE_HANDLER { default?: ROUTE_HANDLER_METHOD; } -const routes: Map = new Map(); +type ROUTE_HANDLER_RECORD = { + route_path: string; + route_pattern: URLPattern; + import_path: string; + module?: ROUTE_HANDLER; +}; +const routes: ROUTE_HANDLER_RECORD[] = []; let loading: boolean = false; let all_routes_loaded: boolean = false; @@ -53,11 +59,7 @@ export default async function handle_typescript(request: Request): Promise 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; - - const pattern = new URLPattern({ pathname: import_info.route_path }); - - if (Deno.env.get('SERVERUS_TYPESCRIPT_IMPORT_LOGGING')) { - console.log(`${import_info.route_path} : 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`); - } - } + routes.push(...imports.sort((lhs, rhs) => rhs.route_path.localeCompare(lhs.route_path))); all_routes_loaded = true; loading = false; @@ -114,11 +104,21 @@ export default async function handle_typescript(request: Request): Promise