make route automatic add the sub routes

This commit is contained in:
rafiarrafif
2025-05-06 15:07:21 +07:00
parent b554ff0e5b
commit a5153f0786
6 changed files with 46 additions and 6 deletions

View File

@ -1,6 +1,7 @@
import { Elysia } from "elysia";
import { routes } from "./routes";
const app = new Elysia().get("/", () => "Hello Elysia").listen(3000);
const app = new Elysia().use(routes).listen(3200);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`

View File

@ -0,0 +1,5 @@
import Elysia from "elysia";
export const getAllUser = (ctx: Elysia) => {
return "Hello User Module";
};

View File

@ -0,0 +1,6 @@
import Elysia from "elysia";
import { getAllUser } from "./controller/getAllUser.controller";
export const userModule = new Elysia({ prefix: "/users" })
.get("/", () => "Hello User Module")
.post("/", () => getAllUser);

View File

@ -1,5 +1,5 @@
import { Context } from "elysia";
export const createUserRole = (ctx: Context) => {
return "OKOK";
return "Hello User Role Module";
};

View File

@ -1,6 +1,6 @@
import Elysia from "elysia";
import { createUserRole } from "./controller/createUserRole.controller";
export const userRoleModule = new Elysia({ prefix: "/user-role" })
export const userRoleModule = new Elysia({ prefix: "/roles" })
.get("/", () => "Hello User Role Module")
.post("/create", createUserRole);
.post("/", createUserRole);

View File

@ -1,4 +1,32 @@
import Elysia from "elysia";
import { userRoleModule } from "./modules/userRole";
import { pathToFileURL } from "bun";
import { readdirSync } from "fs";
import { join } from "path";
export const routes = new Elysia().use(userRoleModule);
const routes = new Elysia();
const modulesPath = join(__dirname, "./modules");
for (const folder of readdirSync(modulesPath, { withFileTypes: true })) {
if (folder.isDirectory()) {
const moduleIndex = join(modulesPath, folder.name, "index.ts");
try {
const module = await import(pathToFileURL(moduleIndex).href);
const mod = Object.values(module).find(
(m): m is Elysia => m instanceof Elysia
);
if (mod) {
routes.use(mod);
}
} catch (error) {
console.warn(
`Module ${folder.name} not found. Please check the module path or name.`
);
}
}
}
export { routes };