resolves errors in filerouter dynamic import

This commit is contained in:
Emmaline Autumn 2025-01-20 20:49:11 -07:00
parent fa73b0bdc0
commit 5de39d8573
5 changed files with 31 additions and 5 deletions

View File

@ -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"
}
}
}

7
fileRouterTest/test.ts Executable file
View File

@ -0,0 +1,7 @@
const handlers = {
get: () => {
return new Response("Hello World");
},
};
export default handlers;

View File

@ -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"),
);
});
}
}
}

View File

@ -73,7 +73,7 @@ import { NotFound } from "./util/response.ts";
* });
*/
export class Router {
private routes: RouteConfig[] = [];
protected routes: RouteConfig[] = [];
private middleware: MiddlewareConfig[] = [];
/**

4
util/isRelativePath.ts Executable file
View File

@ -0,0 +1,4 @@
export function isRelativePath(path: string) {
return !path.startsWith("/") &&
(path.startsWith("./") || path.startsWith("../"));
}