path-to-regexp
path-to-regexp copied to clipboard
Checking if a path is a subset of another path
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