Skip to content

Wrong handling of paths without params #11

@asulykos

Description

@asulykos

Rewrite rules having no parameters, automatically applied to every path (even to the non-matching ones.)

The problem is in getTargetUrl function of util.js.

The toUrl is automatically set to the to parameter, and will be returned even if the path doesn't match. For non-matching paths the intact url parameter should be returned instead.

function getTargetUrl (from, to, url) {
  const { pathToRegexp } = require('path-to-regexp')
  const fromParams = []
  const re = pathToRegexp(from, fromParams)
  const fromMatches = re.exec(url)
  let toUrl = to // <--------- it should be 'url' if 'fromMatches' is undefined

  for (const [index, fromParam] of fromParams.entries()) {
    if (fromMatches && fromMatches[index + 1]) {
      fromParam.value = fromMatches[index + 1]
    }
  }

  /* replace named params */
  for (const fromParam of fromParams) {
    if (typeof fromParam.name === 'string') {
      if (fromParam.value) {
        toUrl = toUrl.replace(new RegExp(`:${fromParam.name}`, 'g'), fromParam.value)
      } else {
        toUrl = url
      }
    }
  }

  /* replace positional params */
  for (const fromParam of fromParams) {
    if (typeof fromParam.name !== 'string') {
      toUrl = url.replace(re, toUrl)
    }
  }

  return toUrl
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions