routeNames.forEach(routeName => {
   let pathPattern =
     pathsByRouteNames[routeName] || routeConfigs[routeName].path;
   let matchExact = !!pathPattern && !childRouters[routeName];
   if (pathPattern === undefined) {
     pathPattern = routeName;
   }
   const keys = [];
   let re, toPath, priority;
   if (typeof pathPattern === 'string') {
     // pathPattern may be either a string or a regexp object according to path-to-regexp docs.
     re = pathToRegexp(pathPattern, keys);
     toPath = pathToRegexp.compile(pathPattern);
     priority = 0;
   } else {
     // for wildcard match
     re = pathToRegexp('*', keys);
     toPath = () => '';
     matchExact = true;
     priority = -1;
   }
   if (!matchExact) {
     const wildcardRe = pathToRegexp(`${pathPattern}/*`, keys);
     re = new RegExp(`(?:${re.source})|(?:${wildcardRe.source})`);
   }
   pathsByRouteNames[routeName] = { re, keys, toPath, priority };
 });
Beispiel #2
0
 /**
  * Make url for a route.
  *
  * @method url
  *
  * @param  {String} urlOrName    - Url, route name or controller action
  * @param  {Object} [data = {}]  - Data object
  * @param  {String} [domain]     - Optional domain
  *
  * @return {String|Null}
  */
 url (routeNameOrHandler, data, domain) {
   const route = RouteStore.find(routeNameOrHandler, domain)
   if (!route) {
     return null
   }
   return pathToRegexp.compile(route._route)(data || {})
 }
Beispiel #3
0
  /**
   * Make url for a route.
   *
   * @method url
   *
   * @param  {String} urlOrName    - Url, route name or controller action
   * @param  {Object} [data = {}]  - Data object
   * @param  {String} [options]    - Other Options
   *
   * @return {String|Null}
   */
  url (routeNameOrHandler, data, options) {
    let normalizedOptions = options || {}

    /**
     * Passing string as 3rd param is depreciated, one must use
     * options object.
     */
    if (typeof (options) === 'string') {
      normalizedOptions = { domain: options }
      console.warn(domainDepreciationMessage(options).join('\n'))
    }

    const route = RouteStore.find(routeNameOrHandler, normalizedOptions.domain)
    if (!route) {
      return null
    }

    const compiledRoute = pathToRegexp.compile(route._route)(data || {})

    /**
     * When domain exists, build a complete url over creating
     * a relative URL.
     */
    if (normalizedOptions.domain) {
      const protocol = _.get(normalizedOptions, 'protocol', 'http')
      return `${protocol}://${normalizedOptions.domain}${compiledRoute}`
    }

    return compiledRoute
  }
Beispiel #4
0
  return routes.map(item => {
    if (!Array.isArray(item))
      throw Error("Route definition must be an array of shape: [pattern, component, options?]");

    const [pattern, type, opts={}] = item;
    let reverse = opts.reverse;
    let re, keys;

    if (typeof type !== "function" && !Array.isArray(type))
      throw Error("Second element must be a React Component or an array of child routes in route definition");

    if (typeof pattern === "string") {
      keys = [];
      re = p2r(pattern, keys, {caseSensitive, strictSlash, end: !Array.isArray(type)});
      if (!keys.length)
        keys = undefined;
      if (!reverse)
        reverse = p2r.compile(pattern);
    } else if (pattern instanceof RegExp) {
      re = pattern;
    }

    if (Array.isArray(type)) {
      return {re, keys, reverse, routes: _prepare(type, {caseSensitive, strictSlash})};
    } else {
      return {re, keys, name: opts.name, reverse, type};
    }
  });
Beispiel #5
0
export function fillParams (
  path: string,
  params: ?Object,
  routeMsg: string
): string {
  params = params || {}
  try {
    // 没缓存就Regexp.compile对path进行处理
    const filler =
      regexpCompileCache[path] ||
      (regexpCompileCache[path] = Regexp.compile(path))

    // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
    if (params.pathMatch) params[0] = params.pathMatch // 特殊情况的处理

    // 填充参数并返回 将参数转化为 /a/b/c
    return filler(params, { pretty: true })
  } catch (e) {
    if (process.env.NODE_ENV !== 'production') {
      warn(false, `missing param for ${routeMsg}: ${e.message}`)
    }
    return '' // 参数解析失败(解析失败)
  } finally {
    // delete the 0 if it was added // 删除之前添加的param
    delete params[0]
  }
}
Beispiel #6
0
 path: function path(name, data) {
     var route;
     route = this.routes[name];
     if (typeof route === 'string') {
         return path2regexp.compile(route)(data);
     }
     return undefined;
 }
Beispiel #7
0
  /**
   * Create a new upload
   */
  beginUpload() {

    let endpoint = pathToRegexp.compile('/imports/api/projects/:projectName/uploads')

    this.showUploadModal(true)
    this.schema('')
    this.newUpload = new Upload({'$url': endpoint(
        {'projectName':this.project.name()})})
  }
Beispiel #8
0
function addApi(siteName){
	var siteConfig = siteManager.getSiteConfig(siteName);
	var prefix = siteName+'/';
	for(var ruleName in siteConfig.rules){
		var rule = siteConfig.rules[ruleName];
		var url = prefix + rule.path;
		var toPath = pathToRegexp.compile(rule.url);
		var apiFunc = new ApiFunc(siteName,ruleName,rule);
		api.get[url] = apiFunc.getFunc();
	}
}
function compilePath(path) {
  if (cache[path]) return cache[path];

  const generator = pathToRegexp.compile(path);

  if (cacheCount < cacheLimit) {
    cache[path] = generator;
    cacheCount++;
  }

  return generator;
}
Beispiel #10
0
 routeNames.forEach((routeName: string) => {
   let pathPattern = paths[routeName] || routeConfigs[routeName].path;
   const matchExact = !!pathPattern && !childRouters[routeName];
   if (typeof pathPattern !== 'string') {
     pathPattern = routeName;
   }
   const keys = [];
   let re = pathToRegexp(pathPattern, keys);
   if (!matchExact) {
     const wildcardRe = pathToRegexp(`${pathPattern}/*`, keys);
     re = new RegExp(`(?:${re.source})|(?:${wildcardRe.source})`);
   }
   /* $FlowFixMe */
   paths[routeName] = { re, keys, toPath: pathToRegexp.compile(pathPattern) };
 });
Beispiel #11
0
var compileGenerator = function compileGenerator(pattern) {
  var cacheKey = pattern;
  var cache = patternCache[cacheKey] || (patternCache[cacheKey] = {});

  if (cache[pattern]) return cache[pattern];

  var compiledGenerator = pathToRegexp.compile(pattern);

  if (cacheCount < cacheLimit) {
    cache[pattern] = compiledGenerator;
    cacheCount++;
  }

  return compiledGenerator;
};
Beispiel #12
0
Router.pathFor = (path, options = {}) => {
  // const params = options.hash || {};
  // const query = params.query ? Router._qs.parse(params.query) : {};
  // // prevent undefined param error
  // for (const i in params) {
  //   if (params[i] === null || params[i] === undefined) {
  //     params[i] = "/";
  //   }
  // }
  // return Router.path(path, params, query);

  const foundPath = Router.routes.find((pathObject) => {
    // console.log(pathObject.options.name, path);
    if (pathObject.options.name === path) {
      return true;
    }
    return false;
  });

  if (foundPath) {
    // Pull the hash out of options
    //
    // This is becuase of Spacebars that we have hash.
    // Spacebars takes all params passed into a template tag and places
    // them into the options.hash object. This will also include any `query` params
    const hash = options && options.hash || {};

    // Create an executable function based on the route regex
    const toPath = pathToRegexp.compile(foundPath.route);

    // Compile the regex path with the params from the hash
    const compiledPath = toPath(hash);

    // Convert the query object to a string
    // e.g. { a: "one", b: "two"} => "a=one&b=two"
    const queryString = queryParse.toString(hash.query);

    // Return the compiled path + query string if we have one
    if (typeof queryString === "string" && queryString.length) {
      return `${compiledPath}?${queryString}`;
    }

    // Return only the compiled path
    return compiledPath;
  }

  return "/";
};
Beispiel #13
0
 const breads = pathArray.map((item, key) => {
   const content = (
     <span>{item.icon
       ? <Icon type={item.icon} style={{ marginRight: 4 }} />
       : ''}{item.name}</span>
   )
   return (
     <Breadcrumb.Item key={key}>
       {((pathArray.length - 1) !== key)
         ? <Link to={pathToRegexp.compile(item.route || '')(paramMap) || '#'}>
           {content}
         </Link>
         : content}
     </Breadcrumb.Item>
   )
 })
Beispiel #14
0
function ApiFunc(siteName,ruleName,rule){
	var toPath = pathToRegexp.compile(rule.url);
	
	this.getFunc = function(){
		return function*(){
			var params = this.params;
			if(rule.defaultParams){
				var defaultParams = copy(rule.defaultParams);
				params = _.merge(defaultParams,params);
			}
			console.log(rule.defaultParams,params);
			var result = yield siteSpider(siteName,rule.ruleName||ruleName,toPath(params));
			this.type = 'application/json';
			this.body = result;
		}
	} 
}
Beispiel #15
0
  // eslint-disable-next-line
  constructRouteUrl(route, { params, query } = {}) {
    const { path } = route;
    const toUrl = PathToRegexp.compile(path);
    let url;
    try {
      url = toUrl(params || {});
    } catch (error) {
      throw new Error(`Framework7: error constructing route URL from passed params:\nRoute: ${path}\n${error.toString()}`);
    }

    if (query) {
      if (typeof query === 'string') url += `?${query}`;
      else url += `?${Utils.serializeObject(query)}`;
    }

    return url;
  }
Router.pathFor = (path, options = {}) => {
  const foundPath = Router.routes.find((pathObject) => {
    if (pathObject.route) {
      if (options.hash && options.hash.shopSlug) {
        if (pathObject.options.name === path && pathObject.route.includes("shopSlug")) {
          return true;
        }
      } else if (pathObject.options.name === path && !pathObject.route.includes("shopSlug")) {
        return true;
      }
    }

    // No path found
    return false;
  });

  if (foundPath) {
    // Pull the hash out of options
    //
    // This is becuase of Spacebars that we have hash.
    // Spacebars takes all params passed into a template tag and places
    // them into the options.hash object. This will also include any `query` params
    const hash = (options && options.hash) || {};

    // Create an executable function based on the route regex
    const toPath = pathToRegexp.compile(foundPath.route);

    // Compile the regex path with the params from the hash
    const compiledPath = toPath(hash);

    // Convert the query object to a string
    // e.g. { a: "one", b: "two"} => "a=one&b=two"
    const queryString = queryParse.toString(hash.query);

    // Return the compiled path + query string if we have one
    if (typeof queryString === "string" && queryString.length) {
      return `${compiledPath}?${queryString}`;
    }

    // Return only the compiled path
    return compiledPath;
  }

  return "/";
};
Beispiel #17
0
  Object.keys(childRouters).forEach(routeName => {
    let pathPattern;

    // First check for paths on the router, then check the route config
    if (pathConfigs[routeName] !== undefined) {
      pathPattern = pathConfigs[routeName];
    } else {
      pathPattern = routeConfigs[routeName].path;
    }

    if (pathPattern === undefined) {
      // If the user hasn't specified a path at all nor disableRouteNamePaths, then we assume the routeName is an appropriate path
      pathPattern = disableRouteNamePaths ? null : routeName;
    }

    invariant(
      pathPattern === null || typeof pathPattern === 'string',
      `Route path for ${routeName} must be specified as a string, or null.`
    );

    // the path may be specified as null, which is similar to empty string because it allows child routers to handle the action, but it will not match empty paths
    const isPathMatchable = pathPattern !== null;
    // pathPattern is a string with inline params, such as people/:id/*foo
    const exactReKeys = [];
    const exactRe = isPathMatchable
      ? pathToRegexp(pathPattern, exactReKeys)
      : null;
    const extendedPathReKeys = [];
    const isWildcard = pathPattern === '' || !isPathMatchable;
    const extendedPathRe = pathToRegexp(
      isWildcard ? '*' : `${pathPattern}/*`,
      extendedPathReKeys
    );

    pathsByRouteNames[routeName] = {
      exactRe,
      exactReKeys,
      extendedPathRe,
      extendedPathReKeys,
      isWildcard,
      toPath: pathPattern === null ? () => '' : compile(pathPattern),
    };
  });
Beispiel #18
0
  this.routes.forEach(route => {
    let keys = pathToRegexp(route.path).keys

    // only attempt this if the route's parameters match those passed to toPath
    let matchingKeys = Object.keys(params).every(param => {
      return keys.filter(key => {
        return key.name === param
      })
    })

    if (matchingKeys) {
      try {
        url = pathToRegexp.compile(route.path)(params)
        error = null
      } catch (err) {
        error = err
      }
    }
  })
Beispiel #19
0
Route.prototype._makePath = function(routePath, params, query) {
    var compiler;
    var url;
    var strQuery;
    if (typeof routePath === 'string') {
        compiler = cachedCompilers[routePath] || pathToRegexp.compile(routePath);
        cachedCompilers[routePath] = compiler;
        url = compiler(params);
        if (query) {
            strQuery = this._queryLib.stringify(query);
            if (strQuery) {
                url += '?' + strQuery;
            }
        }
        return url;
    } else {
        throw new TypeError('route path must be a string:' + routePath);
    }
}
function internalCreateRoutePath(path, completePath, segment) {
  const keys = [];
  const regExp = pathToRegExp(segment ? `${path}/(.+)?` : path, keys, {
    sensitive: true,
    strict: true
  });
  const namedParams = keys.map(key => key.name).filter(Boolean);
  if (segment) return {
    path,
    completePath,
    regExp,
    namedParams
  };
  return {
    path,
    completePath,
    regExp,
    namedParams,
    toPath: pathToRegExp.compile(completePath)
  };
}
      return new Promise(function (resolve, reject) {
        var file = path2regexp.compile(route)(page)
        var directory = path.dirname(file)
        var mkdirPromise, done, result

        mkdirPromise = new Promise(function (resolve, reject) {
          mkdirp(directory, function (err) {
            if (err) {
              reject(err)
            } else {
              resolve()
            }
          })
        })
        .catch(reject)

        done = once(function (err, html) {
          if (err) {
            reject(err)
          } else {
            mkdirPromise.then(function () {
              fs.writeFile(file, html, function (err) {
                if (err) {
                  reject(err)
                } else {
                  resolve(page)
                }
              })
            })
          }
        })

        result = renderer(page, done)

        if (result && typeof result.then === 'function') {
          result.then(function (html) {
            done(null, html)
          }, done)
        }
      })
Beispiel #22
0
Layer.prototype.url = function (params) {
  var args = params;
  var url = this.path;
  var toPath = pathToRegExp.compile(url);

  // argument is of form { key: val }
  if (typeof params != 'object') {
    args = Array.prototype.slice.call(arguments);
  }

  if (args instanceof Array) {
    var tokens = pathToRegExp.parse(url);
    var replace = {};
    for (var len = tokens.length, i=0, j=0; i<len; i++) {
      if (tokens[i].name) replace[tokens[i].name] = args[j++];
    }
    return toPath(replace);
  }
  else {
    return toPath(params);
  }
};
Beispiel #23
0
Layer.prototype.url = function (params, options) {
  var args = params;
  var url = this.path.replace(/\(\.\*\)/g, '');
  var toPath = pathToRegExp.compile(url);
  var replaced;

  if (typeof params != 'object') {
    args = Array.prototype.slice.call(arguments);
    if (typeof args[args.length - 1] == 'object') {
      options = args[args.length - 1];
      args = args.slice(0, args.length - 1);
    }
  }

  var tokens = pathToRegExp.parse(url);
  var replace = {};

  if (args instanceof Array) {
    for (var len = tokens.length, i=0, j=0; i<len; i++) {
      if (tokens[i].name) replace[tokens[i].name] = args[j++];
    }
  } else if (tokens.some(token => token.name)) {
    replace = params;
  } else {
    options = params;
  }

  replaced = toPath(replace);

  if (options && options.query) {
    var replaced = new uri(replaced)
    replaced.search(options.query);
    return replaced.toString();
  }

  return replaced;
};
Beispiel #24
0
function buildPath(path, args) {
  if (R.isNil(path)) {
    return { error: missingArgumentError('path') };
  }

  let compiled;
  try {
    compiled = pathToRegex.compile(path)(args);
  } catch (e) {
    return { error: compilePathError(e) };
  }

  if (!compiled) {
    return { error: invalidArgumentError('path', path) };
  }

  const qp = stringify(R.propOr(undefined, 'queryParams', args));
  if (!R.isEmpty(qp)) {
    compiled = `${compiled}?${qp}`;
  }

  // Note the multiple returns above. If you made it here, it was successful
  return { path: compiled };
}
Beispiel #25
0
    render()
    {
        const {classes, match, history, mails, selectAllMails, deselectAllMails, selectMailsByParameter, setFolderOnSelectedMails, toggleLabelOnSelectedMails, folders, labels, selectedMailIds, currentMail} = this.props;
        const {foldersMenu, selectMenu, labelsMenu} = this.state;
        const toPath = pathToRegexp.compile(match.path);
        const matchParams = {...match.params};
        delete matchParams['mailId'];
        const deselectUrl = toPath(matchParams);

        return (
            <div className={classes.root}>

                <div className={classNames(classes.mailListActions, currentMail && "mail-selected", "flex items-center")}>

                    <Checkbox
                        onChange={this.handleChange()}
                        checked={selectedMailIds.length === Object.keys(mails).length && selectedMailIds.length > 0}
                        indeterminate={selectedMailIds.length !== Object.keys(mails).length && selectedMailIds.length > 0}
                    />

                    <IconButton
                        className={classes.selectMenuButton}
                        aria-label="More"
                        aria-owns={selectMenu ? 'select-menu' : null}
                        aria-haspopup="true"
                        onClick={(ev) => this.handleMenuOpen(ev, 'selectMenu')}
                    >
                        <Icon>arrow_drop_down</Icon>
                    </IconButton>

                    <Menu
                        id="select-menu"
                        anchorEl={selectMenu}
                        open={Boolean(selectMenu)}
                        onClose={(ev) => this.handleMenuClose(ev, 'selectMenu')}
                    >
                        <MenuItem
                            onClick={(ev) => {
                                selectAllMails();
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            All
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                deselectAllMails();
                                this.handleMenuClose(ev, 'selectMenu')
                            }}
                        >
                            None
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('read', true);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Read
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('read', false);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Unread
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('starred', true);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Starred
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('starred', false);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Unstarred
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('important', true);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Important
                        </MenuItem>
                        <MenuItem
                            onClick={(ev) => {
                                selectMailsByParameter('important', false);
                                this.handleMenuClose(ev, 'selectMenu');
                            }}
                        >
                            Unimportant
                        </MenuItem>
                    </Menu>

                    {selectedMailIds.length > 0 && (
                        <React.Fragment>

                            <div className={classes.toolbarSeperator}/>

                            <IconButton
                                onClick={(ev) => setFolderOnSelectedMails(4)}
                                aria-label="Delete"
                            >
                                <Icon>delete</Icon>
                            </IconButton>

                            <IconButton
                                aria-label="More"
                                aria-owns={foldersMenu ? 'folders-menu' : null}
                                aria-haspopup="true"
                                onClick={(ev) => this.handleMenuOpen(ev, 'foldersMenu')}
                            >
                                <Icon>folder</Icon>
                            </IconButton>

                            <Menu
                                id="folders-menu"
                                anchorEl={foldersMenu}
                                open={Boolean(foldersMenu)}
                                onClose={(ev) => this.handleMenuClose(ev, 'foldersMenu')}
                            >
                                {folders.length > 0 && folders.map((folder) => (
                                    <MenuItem
                                        onClick={(ev) => {
                                            setFolderOnSelectedMails(folder.id);
                                            this.handleMenuClose(ev, 'foldersMenu')
                                        }}
                                        key={folder.id}
                                    >
                                        {folder.title}
                                    </MenuItem>
                                ))}
                            </Menu>

                            <IconButton
                                aria-label="More"
                                aria-owns={labelsMenu ? 'labels-menu' : null}
                                aria-haspopup="true"
                                onClick={(ev) => this.handleMenuOpen(ev, 'labelsMenu')}
                            >
                                <Icon>label</Icon>
                            </IconButton>

                            <Menu
                                id="folders-menu"
                                anchorEl={labelsMenu}
                                open={Boolean(labelsMenu)}
                                onClose={(ev) => this.handleMenuClose(ev, 'labelsMenu')}
                            >
                                {labels.length > 0 && labels.map((label) => (
                                    <MenuItem
                                        onClick={(ev) => {
                                            toggleLabelOnSelectedMails(label.id);
                                            this.handleMenuClose(ev, 'labelsMenu')
                                        }}
                                        key={label.id}
                                    >
                                        {label.title}
                                    </MenuItem>
                                ))}
                            </Menu>
                        </React.Fragment>
                    )}
                </div>

                <IconButton className={classNames(classes.deselectMailButton, currentMail && "mail-selected")} onClick={() => history.push(deselectUrl)}>
                    <Icon>arrow_back</Icon>
                </IconButton>
            </div>
        );
    }
module.exports = function(req, options, limits) {
  var requestOptions = _.pick(options,
    'method', 'timeout', 'maxRedirects', 'proxy', 'followRedirect');

  // If an explicit method was not specified on the options, then use the
  // method of the inbound request to the proxy.
  if (!requestOptions.method) {
    requestOptions.method = req.method;
  }

  // Ensure that passed in options for timeout and maxRedirects cannot exceed
  // the platform imposed limits (if defined).
  if (_.isObject(limits) === true) {
    if (_.isNumber(limits.timeout)) {
      if (_.isNumber(options.timeout) === false || options.timeout > limits.timeout) {
        requestOptions.timeout = limits.timeout;
      }
    }
    if (_.isNumber(limits.maxRedirects)) {
      if (_.isNumber(options.maxRedirects) === false ||
        options.maxRedirects > limits.maxRedirects) {
        requestOptions.maxRedirects = limits.maxRedirects;
      }
    }
  }

  // Extend the incoming query with any additional parameters specified in the options
  if (_.isObject(options.query)) {
    _.extend(req.query, options.query);
  }

  var parsedUrl = parseUrl(options.url);

  // Compile the path expression of the originUrl
  var compiledPath = pathToRegexp.compile(parsedUrl.path);

  // Need to decode the path as splat params like 'path/*' will result in an encoded forward slash
  // like http://someapi.com/v1/path1%2Fpath2.
  var pathname = decodeURIComponent(compiledPath(_.extend({}, req.params, options.params || {})));

  // Substitute the actual values using both those from the incoming
  // params as well as those configured in the options. Values in the
  // options take precedence.

  // If options.originalQuery is true, ignore the above and just
  // use the original raw querystring as the search

  requestOptions.url = formatUrl(_.extend({
    protocol: parsedUrl.protocol,
    host: parsedUrl.host,
    pathname: pathname
  }, options.originalQuery ?
    {search: req.url.replace(/^.+\?/, '')} :
    {query: _.extend({}, querystring.parse(parsedUrl.query), req.query, options.query)}
  ));

  requestOptions.headers = {};

  // Passthrough headers
  _.each(req.headers, function(value, key) {
    if (shouldPassthroughHeader(key)) {
      requestOptions.headers[key] = value;
    }
  });

  // Forward the IP of the originating request. This is de-facto proxy behavior.
  if (req.ip) {
    requestOptions.headers['x-forwarded-for'] = req.ip;
  }

  if (req.headers && req.headers.host) {
    var hostSplit = req.headers.host.split(':');
    var host = hostSplit[0];
    var port = hostSplit[1];

    if (port) {
      requestOptions.headers['x-forwarded-port'] = port;
    }

    requestOptions.headers['x-forwarded-host'] = host;
  }

  requestOptions.headers['x-forwarded-proto'] = req.secure ? 'https' : 'http';

  // Default to accepting gzip encoding
  if (!requestOptions.headers['accept-encoding']) {
    requestOptions.headers['accept-encoding'] = 'gzip';
  }

  // Inject additional headers from the options
  if (_.isObject(options.headers)) {
    _.extend(requestOptions.headers, options.headers);
  }

  // Override the user-agent
  if (options.userAgent) {
    requestOptions.headers['user-agent'] = options.userAgent;
  }

  return requestOptions;

  function shouldPassthroughHeader(header) {
    if (_.includes(BLOCK_HEADERS, header) === true) return false;
    if (options.cache && _.includes(CACHE_HEADERS, header) === true) return false;

    return true;
  }
};
Beispiel #27
0
ApiMethod.prototype.makeHref = function(query) {
  query = query || {};
  if (!this._toPath) this._toPath = pathToRegexp.compile(this.fullPath());
  return this._toPath(query);
};
Beispiel #28
0
import ko from 'knockout'
import pathToRegexp from 'path-to-regexp'

import checkStatus from 'utilities/fetch/checkStatus'

const ENDPOINT = pathToRegexp.compile('/imports/api/projects/:projectName?')

export default class Project {

  constructor (params) {
    this.$url = null
    this.$editUrl = null
    this.$deleteUrl = null

    this.name = ko.observable()
    this.title = ko.observable()

    this._update(params)
  }

  _update ({name, title, $url, $editUrl, $deleteUrl}) {
    this.$url = $url
    this.$editUrl = $editUrl
    this.$deleteUrl = $deleteUrl
    this.name(name)
    this.title(title)
  }

  static query (params={}) {
    return fetch(
        ENDPOINT(params),
Beispiel #29
0
  static async getMockAPI (ctx) {
    const { query, body } = ctx.request
    const method = ctx.method.toLowerCase()
    const jsonpCallback = query.jsonp_param_name && (query[query.jsonp_param_name] || 'callback')
    let { projectId, mockURL } = ctx.pathNode
    const redisKey = 'project:' + projectId
    let apiData, apis, api

    apis = await redis.get(redisKey)

    if (apis) {
      apis = JSON.parse(apis)
    } else {
      apis = await MockProxy.find({ project: projectId })
      if (apis[0]) await redis.set(redisKey, JSON.stringify(apis), 'EX', 60 * 30)
    }

    if (apis[0] && apis[0].project.url !== '/') {
      mockURL = mockURL.replace(apis[0].project.url, '') || '/'
    }

    api = apis.filter((item) => {
      const url = item.url.replace(/{/g, ':').replace(/}/g, '') // /api/{user}/{id} => /api/:user/:id
      return item.method === method && pathToRegexp(url).test(mockURL)
    })[0]

    if (!api) ctx.throw(404)

    Mock.Handler.function = function (options) {
      const mockUrl = api.url.replace(/{/g, ':').replace(/}/g, '') // /api/{user}/{id} => /api/:user/:id
      options.Mock = Mock
      options._req = ctx.request
      options._req.params = util.params(mockUrl, mockURL)
      options._req.cookies = ctx.cookies.get.bind(ctx)
      return options.template.call(options.context.currentContext, options)
    }

    if (/^http(s)?/.test(api.mode)) { // 代理模式
      const url = nodeURL.parse(api.mode.replace(/{/g, ':').replace(/}/g, ''), true)
      const params = util.params(api.url.replace(/{/g, ':').replace(/}/g, ''), mockURL)
      const pathname = pathToRegexp.compile(url.pathname)(params)
      try {
        apiData = await axios({
          method: method,
          url: url.protocol + '//' + url.host + pathname,
          params: _.assign({}, url.query, query),
          data: body,
          timeout: 3000
        }).then(res => res.data)
      } catch (error) {
        ctx.body = ctx.util.refail(error.message || '接口请求失败')
        return
      }
    } else {
      const vm = new VM({
        timeout: 1000,
        sandbox: {
          Mock: Mock,
          mode: api.mode,
          template: new Function(`return ${api.mode}`) // eslint-disable-line
        }
      })

      vm.run('Mock.mock(new Function("return " + mode)())') // 数据验证,检测 setTimeout 等方法
      apiData = vm.run('Mock.mock(template())') // 解决正则表达式失效的问题

      /* istanbul ignore else */
      if (apiData._res) { // 自定义响应 Code
        let _res = apiData._res
        ctx.status = _res.status || /* istanbul ignore next */ 200
        /* istanbul ignore else */
        if (_res.cookies) {
          for (let i in _res.cookies) {
            /* istanbul ignore else */
            if (_res.cookies.hasOwnProperty(i)) ctx.cookies.set(i, _res.cookies[i])
          }
        }
        /* istanbul ignore next */
        if (_res.headers) {
          for (let i in _res.headers) {
            /* istanbul ignore next */
            if (_res.headers.hasOwnProperty(i)) ctx.set(i, _res.headers[i])
          }
        }
        /* istanbul ignore next */
        if (_res.status && parseInt(_res.status, 10) !== 200 && _res.data) apiData = _res.data
        delete apiData['_res']
      }
    }

    await redis.lpush('mock.count', api._id)
    if (jsonpCallback) {
      ctx.type = 'text/javascript'
      ctx.body = `${jsonpCallback}(${JSON.stringify(apiData, null, 2)})`
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029') // JSON parse vs eval fix. https://github.com/rack/rack-contrib/pull/37
    } else {
      ctx.body = apiData
    }
  }
Beispiel #30
0
const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options

  const cloneData = lodash.cloneDeep(data)

  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      [domin] = url.match(/[a-zA-z]+:\/\/[^/]*/)
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put':
      return axios.put(url, cloneData)
    case 'patch':
      return axios.patch(url, cloneData)
    default:
      return axios(options)
  }
}