Spaces:
Running
Running
File size: 1,623 Bytes
1628025 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import { Router, Express } from "express";
import { userRoutes } from "./modules/user/index.route";
import { adminRouter } from "./modules/console/index.route";
import * as glob from "glob";
import path from "path";
import { BaseController } from "./lib/controllers/controller.base";
export const setAppRoutes = async (app: Express) => {
const mainRouter = Router();
await importControllers(mainRouter);
setCustomRoutes(mainRouter);
app.use("/api/v1", mainRouter);
};
/* custom routes */
const setCustomRoutes = (router: Router) => {
router.use("/admin", adminRouter);
router.get("/health", (_req: any, res: any) => {
res
.status(200)
.json({ success: true, message: "Server is up!", code: 200 });
});
router.all("*", (_req: any, res: any) => {
res
.status(404)
.json({ success: false, message: "Invalid URL!", code: 404 });
});
};
/* importing all controllers */
const findControllerFiles = (): string[] => {
return glob.sync(path.join(__dirname, "**/*.controller.{ts,js}"));
};
const importControllers = async (router: Router) => {
const files = findControllerFiles();
await Promise.all(
files.map(async (file) => {
const controller = await importController(file);
if (!controller) return;
controller.setRoutes(controller.router);
router.use(controller.prefix, controller.router);
})
);
};
const importController = async (file: string) => {
const controllers = Object.values(await import(file));
return controllers.find(
(controller: { router?: Router }) => controller.router
) as typeof BaseController;
};
|