All files / backend/koa-middleware applyAllRoutes.js

100% Statements 10/10
100% Branches 5/5
100% Functions 2/2
100% Lines 10/10
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 341x 1x   1x                     4x 4x     12x 4x     8x 8x           1x        
const fs = require('fs');
const path = require('path');
 
const DEFAULT_ROUTES_FOLDER = '../routes';
 
/**
 * Loads all JS modules from the `routesFolderPath` and applies them to the koa `app`
 *
 * @category BackEndUtils
 *
 * @param {object} app Instance of `new Koa()`
 * @param {string} routesFolderPath Folder that host all BackEnd API routes
 */
async function applyAllRoutes(app, routesFolderPath = DEFAULT_ROUTES_FOLDER) {
  const basePath = path.join(__dirname, routesFolderPath);
  fs.readdirSync(basePath)
      .forEach((itemPath) => {
        /* Ignore test files and folders */
        if (itemPath === 'test' || itemPath.includes('.spec.')) {
          return;
        }
 
        const router = require(path.join(basePath, itemPath));
        app
            .use(router.routes())
            .use(router.allowedMethods());
      });
}
 
module.exports = {
  DEFAULT_ROUTES_FOLDER,
  applyAllRoutes,
};