Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

优先精确匹配path完全相同的api #326

Open
wants to merge 10 commits into
base: dev
Choose a base branch
from

Conversation

angular-moon
Copy link

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update
  • Refactor
  • Build-related changes
  • Other, please describe:

Does this PR introduce a breaking change?

  • Yes
  • No

If yes, please describe the impact and migration path for existing applications:
优先精确匹配path完全相同的api, 而不是api的定义顺序决定匹配优先级

The PR fulfills these requirements:

  • It's submitted to the dev branch, not the master branch
  • comply with the ESLint configuration of Standard
  • Rebase before creating a PR to keep commit history clear
  • When resolving a specific issue, it's referenced in the PR's title (e.g. fix #xxx[,#xxx], where "xxx" is the issue number)
  • All tests are passing

Other information:

@SoyMeng
Copy link

SoyMeng commented Jul 15, 2019

@angular-moon 做了一个精确匹配的排序,你看看是否更合适

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);
      })
      // 匹配url优先级排序
      .sort(function(a, b) {
        const ap = pathToRegexp.parse(
          a.url.replace(/{/g, ":").replace(/}/g, "")
        );
        const bp = pathToRegexp.parse(
          b.url.replace(/{/g, ":").replace(/}/g, "")
        );
        return ap.length - bp.length;
      })[0];

@angular-moon
Copy link
Author

@SoyMeng 没太看懂, 你写的sort, 是不是写错了, tokens.length 不是都是2吗, 你是想比较url的长度吗?
这个PR是想解决这种问题;
/api/foo/:id
/api/foo/x

需要优先匹配 /api/foo/x, 所以不一定是length长的优先

@SoyMeng
Copy link

SoyMeng commented Jul 15, 2019

@angular-moon 精确匹配根据匹配到的参数数量来判断优先级
/api/foo/:id 参数数量是1
/api/foo/x 参数数量是0

所以匹配/api/foo/x更精确,这个方法不一定完善,但我认为如果需要扩展只需要在sort方法中做优化,至少比===更准确点

@angular-moon
Copy link
Author

@SoyMeng thanks, 按照你的实现修改了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants