all files / dist/satellites/ routes.js

75.94% Statements 101/133
60.56% Branches 43/71
90% Functions 18/20
74.14% Lines 86/116
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                      18×                                                                                                   29×     29×   29×     29×       29× 900×     900×   900× 18×         18×                     18× 18×                                   900× 900× 900× 900×   900× 900×     900×       900× 398×     502× 502× 502×   502×               502×   502×     502×                   502× 484×         18×   18×                               1105×   1105×   1105×                                 12× 12×     12×                                               12×     12×   12× 12×       12×   221×     221× 1105×       12× 221×       12× 12×                               18×   18×     18×                                                                                                                  
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _fs = require('fs');
 
var _fs2 = _interopRequireDefault(_fs);
 
var _utils = require('../utils');
 
var _utils2 = _interopRequireDefault(_utils);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
/**
 * Class to manage the HTTP action routes.
 */
 
var RoutesManager = function () {
 
  /**
   * Create a new RoutesManager instance.
   *
   * @param api API reference.
   */
 
 
  /**
   * Map with the registered routes.
   *
   * @type {{}}
   */
 
  function RoutesManager(api) {
    _classCallCheck(this, RoutesManager);
 
    this.api = null;
    this.routes = { 'get': [], 'post': [], 'put': [], 'patch': [], 'delete': [] };
    this.verbs = ['get', 'post', 'put', 'patch', 'delete'];
 
    var self = this;
 
    // save the API object reference
    self.api = api;
  }
 
  /**
   * Process a route call.
   *
   * @param connection    Connection object.
   * @param pathParts     URI parts.
   */
 
 
  /**
   * Available verbs.
   *
   * @type {string[]}
   */
 
 
  /**
   * API reference.
   *
   * @type {null}
   */
 
 
  _createClass(RoutesManager, [{
    key: 'processRoute',
    value: function processRoute(connection, pathParts) {
      var self = this;
 
      // check if the connection contains an action and that action are defined on the current context
      Eif (connection.params.action === undefined || self.api.actions.actions[connection.params.action] === undefined) {
        // get HTTP request method
        var method = connection.rawConnection.method.toLowerCase();
 
        // if its a 'head' request change it to a 'get'
        if (method === 'head' && !self.routes.head) {
          method = 'get';
        }
 
        // iterate all registered routes
        for (var i in self.routes[method]) {
          var route = self.routes[method][i];
 
          // check if exists an URL match
          var match = self.matchURL(pathParts, route.path, route.matchTrailingPathParts);
 
          if (match.match === true) {
            Iif (route.apiVersion) {
              connection.params.apiVersion = connection.param.apiVersion || route.apiVersion;
            }
 
            // decode URL params
            for (var param in match.params) {
              try {
                var decodedName = decodeURIComponent(param.replace(/\+/g, ' '));
                var decodedValue = decodeURIComponent(match.params[param].replace(/\+g/, ' '));
                connection.params[decodedName] = decodedValue;
              } catch (e) {
                // malformed URL
              }
            }
 
            // put the action in the connection
            connection.params.action = route.action;
            break;
          }
        }
      }
    }
 
    /**
     * Check if the url match with parts.
     *
     * @param pathParts               URL parts to check.
     * @param match                   Route URL to check with.
     * @param matchTrailingPathParts  Check the existence of the path in any part of the URL.
     * @returns {{match: boolean, params: {}}}
     */
 
  }, {
    key: 'matchURL',
    value: function matchURL(pathParts, match, matchTrailingPathParts) {
      var response = { match: false, params: {} };
      var matchParts = match.split('/');
      var regexp = '';
      var variable = '';
 
      Eif (matchParts[0] === '') {
        matchParts.splice(0, 1);
      }
 
      Iif (matchParts[matchParts.length - 1 === '']) {
        matchParts.pop();
      }
 
      if (matchParts.length !== pathParts.length && matchTrailingPathParts !== true) {
        return response;
      }
 
      for (var i in matchParts) {
        var matchPart = matchParts[i];
        var pathPart = pathParts[i];
 
        Iif (matchTrailingPathParts === true && parseInt(i) === matchPart.len - 1) {
          for (var j in pathParts) {
            if (j > i) {
              pathPart = pathPart + '/' + pathParts[j];
            }
          }
        }
 
        Iif (!pathPart) {
          return response;
        } else Iif (matchPart[0] === ':' && matchPart.indexOf('(') < 0) {
          variable = matchPart.replace(':', '');
          response.params[variable] = pathPart;
        } else Iif (matchPart[0] === ':' && matchPart.indexOf('(') >= 0) {
          variable = matchPart.replace(':', '').split('(')[0];
          regexp = matchPart.substring(matchPart.indexOf('(') + 1, matchPart.length - 1);
          var matches = pathPart.match(new RegExp(regexp, 'g'));
          if (matches) {
            response.params[variable] = pathPart;
          } else {
            return response;
          }
        } else {
          if (pathPart === null || pathPart === undefined || pathParts[i].toLowerCase() !== matchPart.toLowerCase()) {
            return response;
          }
        }
      }
 
      response.match = true;
 
      return response;
    }
 
    /**
     * Register a new route.
     *
     * @param method                    HTTP method
     * @param path                      URI
     * @param action                    Action to be executed
     * @param apiVersion                API version
     * @param matchTrailingPathParts
     */
 
  }, {
    key: 'registerRoute',
    value: function registerRoute(method, path, action, apiVersion) {
      var matchTrailingPathParts = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4];
 
      var self = this;
 
      self.routes[method].push({
        path: path,
        matchTrailingPathParts: matchTrailingPathParts,
        action: action,
        apiVersion: apiVersion
      });
    }
 
    /**
     * Load routes.
     *
     * @param rawRoutes
     */
 
  }, {
    key: 'loadRoutes',
    value: function loadRoutes(rawRoutes) {
      var self = this;
      var counter = 0;
 
      // iterate all objects
      for (var i in rawRoutes) {
        // get http method in lower case
        var method = i.toLowerCase();
 
        var _loop = function _loop(j) {
          var route = rawRoutes[i][j];
 
          if (method === 'all') {
            // iterate all http methods
            self.api.routes.verbs.forEach(function (verb) {
              self.api.routes.registerRoute(verb, route.path, route.action, route.apiVersion, route.matchTrailingPathParts);
            });
          } else {
            self.api.routes.registerRoute(method, route.path, route.action, route.apiVersion, route.matchTrailingPathParts);
          }
          counter++;
        };
 
        for (var j in rawRoutes[i]) {
          _loop(j);
        }
      }
 
      // remove duplicated entries on postVariables
      self.api.params.postVariables = _utils2.default.arrayUniqueify(self.api.params.postVariables);
 
      // log the number of loaded routes
      self.api.log(counter + ' routes loaded', 'debug');
 
      Eif (self.api.config.servers.web && self.api.config.servers.web.simpleRouting === true) {
        var simplePaths = [];
 
        // iterate all registered actions
 
        var _loop2 = function _loop2(action) {
          // push the action name to the simples paths
          simplePaths.push('/' + action);
 
          // iterate all verbs
          self.verbs.forEach(function (verb) {
            self.registerRoute(verb, '/' + action, action);
          });
        };
 
        for (var action in self.api.actions.actions) {
          _loop2(action);
        }
 
        // log the number of simple routes loaded
        self.api.log(simplePaths.length + ' simple routes loaded from action names', 'debug');
        self.api.log('routes: ', 'debug', self.routes);
      }
    }
 
    /**
     * Load all modules route files.
     *
     * If the modules have the 'routes.js' file on the module root
     * folder we load that file.
     */
 
  }, {
    key: 'loadModulesRoutes',
    value: function loadModulesRoutes() {
      var self = this;
 
      // iterate all active modules
      self.api.modules.activeModules.forEach(function (moduleName) {
        try {
          // build the file path
          var path = self.api.scope.rootPath + '/modules/' + moduleName + '/routes.js';
 
          // check if the module have a 'routes.js' file
          _fs2.default.accessSync(path, _fs2.default.F_OK);
 
          // get the file content
          var routes = require(path).default;
 
          // load the routes on the engine
          self.loadRoutes(routes);
        } catch (e) {
          // do nothing
        }
      });
 
      // check if we have some routes on the config object
      Eif (self.api.config.routes) {
        self.loadRoutes(self.api.config.routes);
      }
    }
  }]);
 
  return RoutesManager;
}();
 
/**
 * Initializer to load the class who process the routes requests.
 */
 
 
var _class = function () {
  function _class() {
    _classCallCheck(this, _class);
 
    this.loadPriority = 500;
  }
 
  /**
   * Initializer load priority.
   *
   * This only can be loaded after the servers.
   *
   * @type {number}
   */
 
 
  _createClass(_class, [{
    key: 'load',
 
 
    /**
     * Initializer loading function.
     *
     * @param api   API reference.
     * @param next  Callback function.
     */
    value: function load(api, next) {
      // put the routes manager available to all platform
      api.routes = new RoutesManager(api);
 
      // load routes from the config file
      api.routes.loadModulesRoutes();
 
      // finish the initializer loading
      next();
    }
  }]);
 
  return _class;
}();
 
exports.default = _class;
//# sourceMappingURL=routes.js.map