All files / router path-to-regexp-wrap.js

20% Statements 4/20
25% Branches 2/8
25% Functions 1/4
20% Lines 4/20
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                      1x           1x 2x                               2x                                              
// This comes from https://github.com/teologov/path-to-regexp-wrap
// because of this bug: https://github.com/franciscop/server/issues/43
 
/**
 * Path to regexp lib wrapper
 * @author Andrey Teologov <teologov.and@gmail.com>
 * @date 16.04.14
 */
 
"use strict";
 
const path = require('path-to-regexp');
 
/**
 * Routes lib
 * @type {exports}
 */
module.exports = function(options) {
  options = options || {};
 
  /**
   * String decoder
   * @param {String} str
   * @returns {*}
   */
  function decodeUri(str) {
    try {
      str = decodeURIComponent(str);
    } catch(e) {
      throw new Error(`Cannot decodeURIComponent: ${str}` );
    }
    return str;
  }
 
  return function(route) {
    const keys = [];
    const reg = path.apply(this, [route, keys, options]);
 
    return function(route, config) {
      const res = reg.exec(route);
      const params = config || {};
 
      if (!res) {
        return false;
      }
 
      for (let i = 1, l = res.length; i < l; i++) {
        if (!res[i]) {
          continue;
        }
        params[keys[i - 1].name] = decodeUri(res[i]);
      }
 
      return params;
    }
  }
};