Skip to content

Commit

Permalink
Add back keys property to regex
Browse files Browse the repository at this point in the history
The returned regex object from `pathToRegex` used to include the modified
keys array as a `keys` property in v1.7.0. The current API is not entirely
ideal, since a keys array must be passed, we could instead use a more
functional API where no array is mutated.

In the future this should be changed that no array needs to be passed to
`pathToRegex`, adding it as a property is done for backwards compatibility.
  • Loading branch information
nickyu42 committed Mar 8, 2022
1 parent 762bc6b commit 845c7fb
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,13 @@ export function match<P extends object = object>(
return regexpToFunction<P>(re, keys, options);
}

export interface RegExpWithKeys extends RegExp {
/**
* Optional property that includes key metadata corresponding to this regex.
*/
keys?: Key[];
}

/**
* Create a path match function from `path-to-regexp` output.
*/
Expand Down Expand Up @@ -479,9 +486,14 @@ function arrayToRegexp(
paths: Array<string | RegExp>,
keys?: Key[],
options?: TokensToRegexpOptions & ParseOptions
): RegExp {
): RegExpWithKeys {
const parts = paths.map((path) => pathToRegexp(path, keys, options).source);
return new RegExp(`(?:${parts.join("|")})`, flags(options));
const re: RegExpWithKeys = new RegExp(
`(?:${parts.join("|")})`,
flags(options)
);
re.keys = keys;
return re;
}

/**
Expand Down Expand Up @@ -533,7 +545,7 @@ export function tokensToRegexp(
tokens: Token[],
keys?: Key[],
options: TokensToRegexpOptions = {}
) {
): RegExpWithKeys {
const {
strict = false,
start = true,
Expand Down Expand Up @@ -596,7 +608,10 @@ export function tokensToRegexp(
}
}

return new RegExp(route, flags(options));
const re: RegExpWithKeys = new RegExp(route, flags(options));
re.keys = keys;

return re;
}

/**
Expand Down

0 comments on commit 845c7fb

Please sign in to comment.