Search code examples
node.jskoakoa-router

How can I split my koa routes into separate files? Middleware problem


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.


Solution

  • Issue solved as by own. Previously i used to combine routes with middleware also in the same line.

    router.use(middleware.isAuthorized, routesFile.routes(), routesFile.allowedMethods());
    

    But that's the wrong way I used to define route. router.use() uses the middleware to all the routes. So now i just splitted my routes into separate router use with individual path. Mentioned in the document Koa router

    Solved answer

    fs.readdirSync(__dirname)
      .filter(file => (file.indexOf(".") !== 0 && file !== '__index.js' && file.slice(-3) === ".js"))
      .forEach(file => {
        const routesFile = require(`${__dirname}/${file}`);
        if (file !== 'auth.js') {
          routesFile.stack.forEach(elem => { router.use(elem.path, middleware.isAuthorized); });
        }
        router.use(routesFile.routes(), routesFile.allowedMethods());
      });