diff --git a/deno.json b/deno.json index 79d7b9b..c0102b1 100755 --- a/deno.json +++ b/deno.json @@ -1,7 +1,7 @@ { "name": "@bearmetal/router", "description": "A simple router for Deno", - "version": "0.2.2", + "version": "0.2.3-a", "stable": true, "files": [ "mod.ts", @@ -20,4 +20,4 @@ "@std/assert": "jsr:@std/assert@^1.0.7", "@std/testing": "jsr:@std/testing@^1.0.4" } -} \ No newline at end of file +} diff --git a/fileRouterTest/test.ts b/fileRouterTest/test.ts new file mode 100755 index 0000000..e20b0ab --- /dev/null +++ b/fileRouterTest/test.ts @@ -0,0 +1,7 @@ +const handlers = { + get: () => { + return new Response("Hello World"); + }, +}; + +export default handlers; diff --git a/file_router.ts b/file_router.ts index b053cd7..e20b723 100755 --- a/file_router.ts +++ b/file_router.ts @@ -1,5 +1,6 @@ import Router from "./router.ts"; import type { Handler, RouteConfigurator } from "./types.ts"; +import { isRelativePath } from "./util/isRelativePath.ts"; function crawl(dir: string, callback: (path: string) => void) { for (const entry of Deno.readDirSync(dir)) { @@ -27,10 +28,15 @@ export class FileRouter extends Router { constructor(root: string) { super(); crawl(root, async (path) => { - let relativePath = path.replace(root, ""); + let relativePath = path.replace(root, "").replace(/index\/?/, ""); if (path.endsWith(".ts") || path.endsWith(".js")) { + if (isRelativePath(path)) { + path = Deno.build.os === "windows" + ? `${Deno.cwd()}\\${path.replace(/^.?.?\\/, "")}` + : `${Deno.cwd()}/${path.replace(/^.?.?\//, "")}`; + } relativePath = relativePath.replace(/\.[tj]s/, ""); - const handlers = await import(path); + const handlers = await import("file://" + path); if (handlers.default) { handlers.default instanceof Router @@ -55,6 +61,15 @@ export class FileRouter extends Router { }); } }); + + if (Deno.env.get("BEARMETAL_ROUTER_DEBUG") === "true") { + this.route("/debug/dump").get((_ctx) => { + console.log("Dumping routes:"); + return new Response( + this.routes.map((r) => r.pattern.pathname).join("\n"), + ); + }); + } } } diff --git a/router.ts b/router.ts index be930b2..37808f0 100755 --- a/router.ts +++ b/router.ts @@ -73,7 +73,7 @@ import { NotFound } from "./util/response.ts"; * }); */ export class Router { - private routes: RouteConfig[] = []; + protected routes: RouteConfig[] = []; private middleware: MiddlewareConfig[] = []; /** diff --git a/util/isRelativePath.ts b/util/isRelativePath.ts new file mode 100755 index 0000000..5649c00 --- /dev/null +++ b/util/isRelativePath.ts @@ -0,0 +1,4 @@ +export function isRelativePath(path: string) { + return !path.startsWith("/") && + (path.startsWith("./") || path.startsWith("../")); +}