Checking if a path is a subset of another path
MatthiasKunnen opened this issue · comments
Given two paths, e.g. /foo/bar
and /foo/(.*)
, I would like to check if the former is a subset of the latter. In other words, determine whether all requests matched by one path would also be matched by another.
To my understanding this is not currently possible using path-to-regexp
.
Suggested method:
/**
* Returns true if the given `subsetPath` is a subset of the given path. False otherwise.
* @example /foo /:slug -> true
* @example /:slug /(.*) -> true
* @example /foo/bar /foo/(.*) -> true
* @example /foo/bar /foo -> false
* @example /foo /foo/bar -> false
*/
function isSubset(subsetPath: string, path: string): boolean {
}
Use case
Say there are both routes and middleware, having such a function would allow for checking if a middleware path applies to a route.
It would also allow for filtering a list of paths based on another path like so:
const result = [
'/foo/:view',
'/bar',
'/foo/hello',
'/foo/contact/(.*)',
'/baz',
].filter(path => isSubset(path, '/foo/(.*)'))
// result:
// [
// '/foo/:view',
// '/foo/hello',
// '/foo/contact/(.*)',
// ]
Search keywords: regex subset of another, compare paths, path matched by another path
It sounds interesting but too difficult for me to build correctly right now, so I'm going to close the issue. The main problem is that I'd have to build something that actually parses and understands regexes. This sounds better left to a user land module instead, since the path-to-regexp
parser is already exposed so it'd just need to compare the parsed results. That's all fairly easy until you need to figure out if [a-z]
is a subset of \d
or \p{L}
, etc. There's a lot of combinations when you open the regex can of worms here.