How to use path-to-regexp - 10 common examples

To help you get started, we’ve selected a few path-to-regexp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dadi / web / test / unit / page.js View on Github external
paths.forEach(function(path) {
      p.routes = [path]

      var tokens = pathToRegexp.parse(path.path)
      var parts = {}

      // console.log(tokens)
      tokens.forEach(function(token) {
        if (typeof token === "object") {
          parts[token.name] = "whatever"
        }
      })

      var url = p.toPath(parts)
      var expected = pathToRegexp.compile(path.path)(parts)
      // console.log(url)

      url.should.eql(expected)
    })
github herton7362 / dynamic-menu-pro / src / common / router.js View on Github external
Object.keys(routerConfig).forEach(path => {
    // Regular match item name
    // eg.  router /user/:id === /user/chen
    const pathRegexp = pathToRegexp(path);
    const menuKey = Object.keys(menuData).find(key => pathRegexp.test(`${key}`));
    let menuItem = {};
    // If menuKey is not empty
    if (menuKey) {
      menuItem = menuData[menuKey];
    }
    let router = routerConfig[path];
    // If you need to configure complex parameter routing,
    // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
    // eg . /list/:type/user/info/:id
    router = {
      ...router,
      name: router.name || menuItem.name,
      authority: router.authority || menuItem.authority,
      hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb,
    };
github Dromara / soul-dashboard / src / common / router.js View on Github external
Object.keys(routerConfig).forEach(path => {
    // Regular match item name
    // eg.  router /user/:id === /user/chen
    const pathRegexp = pathToRegexp(path);
    const menuKey = Object.keys(menuData).find(key => pathRegexp.test(`${key}`));
    let menuItem = {};
    // If menuKey is not empty
    if (menuKey) {
      menuItem = menuData[menuKey];
    }
    let router = routerConfig[path];
    // If you need to configure complex parameter routing,
    // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
    // eg . /list/:type/user/info/:id
    router = {
      ...router,
      name: router.name || menuItem.name,
      authority: router.authority || menuItem.authority,
      hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb,
    };
github zeit / next.js / packages / next / lib / check-custom-routes.ts View on Github external
if (isRedirect) {
      const redirRoute = route as Redirect

      if (
        redirRoute.statusCode &&
        !allowedStatusCodes.has(redirRoute.statusCode)
      ) {
        hadInvalidStatus = true
        invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`)
      }
    }

    try {
      // Make sure we can parse the source properly
      regexpMatch(route.source)
    } catch (err) {
      // If there is an error show our err.sh but still show original error
      console.error(
        `\nError parsing ${route.source} https://err.sh/zeit/next.js/invalid-route-source`,
        err
      )
    }

    const hasInvalidKeys = invalidKeys.length > 0
    const hasInvalidParts = invalidParts.length > 0

    if (hasInvalidKeys || hasInvalidParts) {
      console.error(
        `${invalidParts.join(', ')}${
          invalidKeys.length
            ? (hasInvalidParts ? ',' : '') +
github thinkjs / pharos / www / static / src / models / perf.js View on Github external
const { pathname, query } = routing;
      let param = {
        ...query,
        site_id: currentSite.id,
        // end_time: moment().format('YYYY-MM-DD'),//最近7天
        // start_time: moment().subtract(7, 'days').format('YYYY-MM-DD')
      }
      // if (!query.site_id && sites.length > 0) {
      //   yield put(routerRedux.push({
      //     pathname,
      //     query: param
      //   }))
      //   return;
      // }
      if (pathname.indexOf('/perf/specific') > -1 && !param.type) {
        const match = pathToRegexp('/perf/specific/:type').exec(location.pathname);  
        if (match) {
          param.type = match[1];
        }
      }
      yield put({ type: 'query', payload: param });
    },
    *query({ payload = {} }, { call, put }) {
github reactioncommerce / reaction / imports / plugins / core / router / client / browserRouter.js View on Github external
// If no matching path is found, fetch the not-found route definition
    if (foundPaths.length === 0 && location.pathname !== "not-found") {
      foundPaths = Router.routes.filter((pathObject) => matchPath("/not-found", {
        path: pathObject.route,
        exact: true
      }));
    }

    // If we have a found path, take the first match
    const foundPath = foundPaths.length && foundPaths[0];
    const params = {};

    // Process the params from the found path definiton
    if (foundPath) {
      const keys = [];
      const re = pathToRegexp(foundPath.route, keys); // Create parser with route regex
      const values = re.exec(location.pathname); // Process values

      // Create params object
      keys.forEach((key, index) => {
        params[key.name] = values[index + 1];
      });
    }

    // Get serach (query) string from current location
    let { search } = location;

    // Remove the ? if it exists at the beginning
    if (typeof search === "string" && search.startsWith("?")) {
      search = search.substr(1);
    }
github spaceavocado / svelte-router / src / router.js View on Github external
}

      // Generate the regex matcher and params keys
      routes[i].paramKeys = [];
      // Any URL
      if (routes[i].path == '*') {
        routes[i].matcher = /.*/i;
        routes[i].generator = () => '/';
      // Regex based
      } else {
        routes[i].matcher = pathToRegexp(
            routes[i].path,
            routes[i].paramKeys, {
              end: routes[i].children.length == 0,
            });
        routes[i].generator = pathToRegexp.compile(routes[i].path);
      }

      // Process children
      if (routes[i].children.length > 0) {
        this._preprocessRoutes(routes[i].children, routes[i]);
      }
    }
  }
github yqsailor / react-antd-admin / src / utils / request.js View on Github external
let {
    data,
    url,
  } = options;

  const cloneData = lodash.cloneDeep(data);

  try {
    let domin = '';
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0];
      url = url.slice(domin.length);
    }
    const match = pathToRegexp.parse(url);
    url = pathToRegexp.compile(url)(data);
    for (const item of match) {
      // eslint-disable-next-line
      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()}`,
github kythe / kythe / kythe / typescript / languageserver / languageserver / src / pathContext.ts View on Github external
function compilePath(path: string): PathMapping {
  // Prefix all the path patterns with / because path-to-regexp requires one
  path = '/' + path;

  const cons = p2r.compile(path);

  // Because the patterns were prefixed with slashes, we remove them on construction
  return {re: p2r(path), cons: (params: Params) => cons(params).substring(1)};
}
github rill-js / rill / src / index.ts View on Github external
function toReg(pathname: string, keys: any[], options: any): RegExp {
  // First parse path into tokens.
  const tokens = parse(pathname);

  // Find the last token (checking for splat params).
  const splat: any = tokens[tokens.length - 1];

  // Check if the last token is a splat and make it optional.
  if (splat && splat.asterisk) {
    splat.optional = true;
  }

  // Convert the tokens to a regexp.
  const re = tokensToRegExp(tokens, options);

  // Assign keys to from regexp.
  (re as any).keys = keys;
  for (let i = 0, len = tokens.length; i < len; i++) {
    if (typeof tokens[i] === "object") {