Source: resolver.js

/**
 * @file resolves local source files to map them to api path's and methods
 * @author Florian Schaper <f.schaper@reply.de>
 * @copyright Florian Schaper 2018, MIT License
 */

const filePath = require('path');

/**
 * resolved an api specification to local source files and exported method handlers
 *
 * @param {Object} options
 * @param {string} options.basePath - base filename to look for controllers to match with the api spec
 * @returns {ExpressHandler} express callback handler
 * @throws Error in case that a controller or method could not be resolved
 */
function resolver({ basePath }) {
  return ({ path, method, options }) => {
    let handler;
    try {
      const controllerPath = filePath.resolve(basePath, options['x-controller'] || filePath.join(...path.split('/')));
      // disable the security warning since the resolver will not be used after initial route configuration
      // we also ignore the warning regarding require since we fully intend to make use of e.g. requires caching functionality.
      // eslint-disable-next-line security/detect-object-injection, security/detect-non-literal-require, global-require
      handler = require(controllerPath)[method];
    } catch (e) {
      throw new Error(`could not resolve controller for path ${path}`);
    }
    if (!handler) {
      throw new Error(`could not resolve required method ${method} in controller for path ${path}`);
    }
    return handler;
  };
}

module.exports = resolver;