Skip to content

Commit

Permalink
implement with simple regex matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Oct 4, 2023
1 parent 5fdecab commit c3aa794
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
15 changes: 10 additions & 5 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ function lookup(ctx: RadixRouterContext, path: string): MatchedRoute {
if (node === null) {
break;
} else {
params[node.paramName] = section;
if (node.type === NODE_TYPES.MIXED && node.paramMatcher) {
const matches = section.match(node.paramMatcher);
Object.assign(params, matches.groups);
} else {
params[node.paramName] = section;
}
paramsFound = true;
}
} else {
Expand Down Expand Up @@ -125,11 +130,11 @@ function insert(ctx: RadixRouterContext, path: string, data: any) {
childNode.paramName = params[0].slice(1);
} else {
childNode.type = NODE_TYPES.MIXED;
childNode.mixedParams = params.map((p) =>
p[0] === ":"
? { type: "dynamic", name: p.slice(1) }
: { type: "static", name: p }
const sectionRegexString = section.replace(
/:(\w+)/g,
(_, id) => `(?<${id}>\\w+)`,
);
childNode.paramMatcher = new RegExp(`^${sectionRegexString}$`);
}
}
node.placeholderChildNode = childNode;
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface RadixNode<T extends RadixNodeData = RadixNodeData> {
children: Map<string, RadixNode<T>>;
data: RadixNodeData | null;
paramName: string | null;
mixedParams?: { type: "static" | "dynamic"; name: string }[];
paramMatcher?: string | RegExp;
wildcardChildNode: RadixNode<T> | null;
placeholderChildNode: RadixNode<T> | null;
}
Expand Down
4 changes: 2 additions & 2 deletions tests/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ describe("Router lookup", function () {
});

describe("mixed params in same segemnt", function () {
const mixedPath = "/files/:category/:id,name:name.txt";
const mixedPath = "/files/:category/:id,name=:name.txt";
testRouter([mixedPath], {
"/files/test/id:123,name=foobar.txt": {
"/files/test/123,name=foobar.txt": {
path: mixedPath,
params: { category: "test", id: "123", name: "foobar" },
},
Expand Down

0 comments on commit c3aa794

Please sign in to comment.