Am trying to split koa routes into separate files. I'm having folder structure like this for routes.
routes/
__index.js
auth.js
user.js
So if trying with method one means it's working perfectly. But going with dynamic way that is method 2 means it's not working properly. All routes getting hitting, that's not the problem, but at the same time for auth route also it's going inside middleware.isAuthorized.
Method 1
const routesToEnable = {
authRoute: require('./auth'),
userRoute: require('./user')
};
for (const routerKey in routesToEnable) {
if (routesToEnable[routerKey]) {
const nestedRouter = routesToEnable[routerKey];
if (routerKey == 'authRoute') {
router.use(nestedRouter.routes(), nestedRouter.allowedMethods());
} else {
router.use(middleware.isAuthorized, nestedRouter.routes(), nestedRouter.allowedMethods());
}
}
}
module.exports = router;
Method 2
fs.readdirSync(__dirname)
.filter(file => (file.indexOf(".") !== 0 && file !== '__index.js' && file.slice(-3) === ".js"))
.forEach(file => {
// console.info(`Loading file ${file}`);
const routesFile = require(`${__dirname}/${file}`);
switch (file) {
case 'auth.js':
router.use(routesFile.routes(), routesFile.allowedMethods());
break;
default:
router.use(middleware.isAuthorized, routesFile.routes(), routesFile.allowedMethods());
break;
}
});
module.exports = router;
How can i use method two without middleware for auth route itself. Can anyone please suggest what I'm doing wrong here. Thanks in advance.