kitze / mobx-router

A simple router for MobX + React apps
509 stars 66 forks source link

this.path RegExp shouldn't match word prefixes #34

Open sadasant opened 7 years ago

sadasant commented 7 years ago

The RegExp used when this.path has optional parameters is currently matching word prefixes. For example, if a route's originalPath is /person/:id?, it is right now matching /persons, but it shouldn't. This behavior is specially bad when a page is using routes like /person/:id? and /persons/:type?, in which case, if anyone types /persons, the route that gets called is /person/:id?, and not the correct one.

Here's a simple proof of the problem:

> (new RegExp('/request/?([^/]*)?$')).test('/request')
true
> (new RegExp('/request/?([^/]*)?$')).test('/requests')
true

And here's an example of the correct behavior (achieved by the proposed change):

> (new RegExp('/request(/([^/]*)?)?$')).test('/request')
true
> (new RegExp('/request(/([^/]*)?)?$')).test('/requests')
false

Please review! I'd like to make this even better if posible 👍

I'm sorry that I didn't include any test for this. I did a quick look and I didn't find any specific test for the regexps. However, I'm willing to write one if necessary!

Thanks for the time and effort ✌️