Skip to content

Instantly share code, notes, and snippets.

@aindong
Created March 21, 2022 05:56
Show Gist options
  • Save aindong/0fb1c3fc22f3cc38c4b1d49a97366a95 to your computer and use it in GitHub Desktop.
Save aindong/0fb1c3fc22f3cc38c4b1d49a97366a95 to your computer and use it in GitHub Desktop.
Dynamic Routing on Express JS
import express, { Response, Request } from 'express';
import fs from 'fs';
import { IRouterSettings } from './interfaces/IRouterSettings';
import Logger from './utils/logger';
const router = express.Router();
// loop through all the routes
const controllersPath = `${__dirname}/controllers`;
const controllers = fs.readdirSync(controllersPath);
controllers.forEach(async controller => {
try {
// router settings path
const routeSettingsPath = `${__dirname}/controllers/${controller}/router.json`;
const routeFile = fs.readFileSync(routeSettingsPath, 'utf8');
if (!routeFile) {
return;
}
// Read the route settings
const json = JSON.parse(routeFile) as IRouterSettings;
// iterate all paths from json
json.routes.forEach(route => {
const path = `${json.prefix}/${route.path}`.replace(/\/\//g, '/');
Logger.info(`[Router] Adding route ${path}`);
// remove trailing slash
const handler = route.handler.split('.');
const controllerFile = handler[0];
const methodName = handler[1];
// create router
router.use(path, async (req: Request, res: Response) => {
// Check method
if (req.method !== route.method) {
return res.status(405).json({
message: `Method ${req.method} not allowed`,
});
}
try {
// eslint-disable-next-line global-require
const ControllerModule = require(`${__dirname}/controllers/${controller}/${controllerFile}`);
console.log('controller class', ControllerModule);
// check if Controller Module is a class
if (typeof ControllerModule !== 'function') {
return res.status(500).json({
message: `${controllerFile} is not a class`,
});
}
const controllerInstance = new ControllerModule(req, res);
// check if function exists on ControllerModule
if (!controllerInstance[methodName]) {
return res.status(404).json({
message: `Method ${methodName} not found`,
});
}
return controllerInstance[methodName]();
} catch (error) {
return res.status(500).json({
message: `${controller} Something went wrong`,
});
}
});
});
// console.log(controller);
// console.log(json);
} catch (error) {
Logger.error(`Error on ${controller} no router.json found`);
}
});
export default router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment