Files
aaaa/src/util/import.ts
2025-09-06 22:22:36 -04:00

53 lines
1.7 KiB
TypeScript

import Logging from "@proxnet/undead-logging";
import { Hono } from "@hono/hono";
import path from "node:path";
import process from "node:process";
import { HonoEnv, RouteImport } from "./types.ts";
const debug = false;
export async function routeImporter(hono: Hono<HonoEnv>, prefix: string, paths: string[]) {
const items = await importer<RouteImport>('route', prefix, paths);
for (const route of items) hono.route(route.path, route.app);
}
export async function importer<T>(importKey: string, prefix: string, paths: string[]): Promise<T[]> {
const log = new Logging(`Importer:'${importKey}'-${prefix}`);
const items: T[] = [];
for (const pathStr of paths) {
const importPath = path.join(process.cwd(), prefix, pathStr);
if (debug) log.d(`'${importKey}' found ${importPath}`);
for await (const localPath of Deno.readDir(importPath)) {
if (localPath.isDirectory) continue;
if (localPath.isFile && localPath.name.endsWith('.ts')) {
const fullPath = path.join('file://', importPath, localPath.name);
if (debug) log.d(`'${importKey}' importing ${fullPath}`);
await import(fullPath).then(val => {
if (val[importKey]) items.push(val[importKey]);
else log.w(`Import key '${importKey}' not found on: '${fullPath}'`);
}).catch(err => {
log.e(`Could not import key '${importKey}' from ${fullPath}: ${err}`);
});
}
}
}
return items;
}
export function createHonoRoute(path: string) {
const route: RouteImport = {
path,
app: new Hono<HonoEnv>()
}
return route;
}