Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: findAllRoutes #117

Merged
merged 6 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import {
addRoute,
findRoute,
removeRoute,
matchAllRoutes,
findAllRoutes,
} from "rou3";
```

Expand All @@ -63,7 +63,7 @@ const {
addRoute,
findRoute,
removeRoute,
matchAllRoutes,
findAllRoutes,
} = require("rou3");
```

Expand All @@ -75,7 +75,7 @@ import {
addRoute,
findRoute,
removeRoute,
matchAllRoutes,
findAllRoutes,
} from "https://esm.sh/rou3";
```

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@
"dist"
],
"scripts": {
"bench:bun": "bun ./test/bench",
"bench:node": "node --import jiti/register ./test/bench",
"build": "unbuild",
"dev": "vitest",
"bench:node": "node --import jiti/register ./test/bench",
"bench:bun": "bun ./test/bench",
"lint": "eslint . && prettier -c src test",
"lint:fix": "automd && eslint --fix . && prettier -w src test",
"release": "pnpm test && pnpm build && changelogen --release && git push --follow-tags && npm publish",
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ export type { RouterContext } from "./types";
export { addRoute } from "./operations/add";
export { findRoute } from "./operations/find";
export { removeRoute } from "./operations/remove";
export { matchAllRoutes } from "./operations/match";
export { findAllRoutes } from "./operations/find-all";
24 changes: 24 additions & 0 deletions src/operations/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
import type { MatchedRoute, ParamsIndexMap } from "../types";

export function splitPath(path: string) {
return path.split("/").filter(Boolean);
}

export function getMatchParams(
segments: string[],
paramsMap: ParamsIndexMap,
): MatchedRoute["params"] {
const params = Object.create(null);
for (const [index, name] of paramsMap) {
const segment =
index < 0 ? segments.slice(-1 * index).join("/") : segments[index];
if (typeof name === "string") {
params[name] = segment;
} else {
const match = segment.match(name);
if (match) {
for (const key in match.groups) {
params[key] = match.groups[key];
}
}
}
}
return params;
}
15 changes: 9 additions & 6 deletions src/operations/add.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RouterContext, Params } from "../types";
import type { RouterContext, ParamsIndexMap } from "../types";
import { splitPath } from "./_utils";

/**
Expand All @@ -16,7 +16,7 @@ export function addRoute<T>(

let _unnamedParamIndex = 0;

const params: Params = [];
const paramsMap: ParamsIndexMap = [];

for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
Expand All @@ -27,7 +27,7 @@ export function addRoute<T>(
node.wildcard = { key: "**" };
}
node = node.wildcard;
params.push([-i, segment.split(":")[1] || "_"]);
paramsMap.push([-i, segment.split(":")[1] || "_"]);
break;
}

Expand All @@ -37,7 +37,7 @@ export function addRoute<T>(
node.param = { key: "*" };
}
node = node.param;
params.push([
paramsMap.push([
i,
segment === "*"
? `_${_unnamedParamIndex++}`
Expand All @@ -61,11 +61,14 @@ export function addRoute<T>(
}

// Assign index, params and data to the node
const hasParams = params.length > 0;
const hasParams = paramsMap.length > 0;
if (!node.methods) {
node.methods = Object.create(null);
}
node.methods![method] = [data || (null as T), hasParams ? params : undefined];
node.methods![method] = {
data: data || (null as T),
paramsMap: hasParams ? paramsMap : undefined,
};
node.index = segments.length - 1;

// Static
Expand Down
75 changes: 75 additions & 0 deletions src/operations/find-all.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { RouterContext, Node, MatchedRoute, MethodData } from "../types";
import { getMatchParams, splitPath } from "./_utils";

/**
* Find all route patterns that match the given path.
*/
export function findAllRoutes<T>(
ctx: RouterContext<T>,
method: string = "",
path: string,
opts?: { params?: boolean },
): MatchedRoute<T>[] {
if (path[path.length - 1] === "/") {
path = path.slice(0, -1);
}
const segments = splitPath(path);
const _matches = _findAll(ctx, ctx.root, method, segments, 0);
const matches: MatchedRoute<T>[] = [];
for (const match of _matches) {
matches.push({
data: match.data,
params:
opts?.params && match.paramsMap
? getMatchParams(segments, match.paramsMap)
: undefined,
});
}
return matches;
}

function _findAll<T>(
ctx: RouterContext<T>,
node: Node<T>,
method: string,
segments: string[],
index: number,
matches: MethodData<T>[] = [],
): MethodData<T>[] {
const segment = segments[index];

// 1. Wildcard
if (node.wildcard && node.wildcard.methods) {
const match = node.wildcard.methods[method] || node.wildcard.methods[""];
if (match) {
matches.push(match);
}
}

// 2. Param
if (node.param) {
_findAll(ctx, node.param, method, segments, index + 1, matches);
if (index === segments.length && node.param.methods) {
const match = node.param.methods[method] || node.param.methods[""];
if (match) {
matches.push(match);
}
}
}

// 3. Static
const staticChild = node.static?.[segment];
if (staticChild) {
_findAll(ctx, staticChild, method, segments, index + 1, matches);
}

// 4. End of path
if (index === segments.length && node.methods) {
const match = node.methods[method] || node.methods[""];
if (match) {
matches.push(match);
}
}

return matches;
}
53 changes: 16 additions & 37 deletions src/operations/find.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { RouterContext, MatchedRoute, Node, Params } from "../types";
import { splitPath } from "./_utils";
import type { RouterContext, MatchedRoute, Node, MethodData } from "../types";
import { getMatchParams, splitPath } from "./_utils";

/**
* Find a route by path.
Expand All @@ -8,7 +8,7 @@ export function findRoute<T = unknown>(
ctx: RouterContext<T>,
method: string = "",
path: string,
opts?: { ignoreParams?: boolean },
opts?: { params?: boolean },
): MatchedRoute<T> | undefined {
if (path[path.length - 1] === "/") {
path = path.slice(0, -1);
Expand All @@ -19,38 +19,39 @@ export function findRoute<T = unknown>(
if (staticNode && staticNode.methods) {
const staticMatch = staticNode.methods[method] || staticNode.methods[""];
if (staticMatch !== undefined) {
return { data: staticMatch[0] };
return staticMatch;
}
}

// Lookup tree
const segments = splitPath(path);
const match = _lookupTree(ctx, ctx.root, method, segments, 0);

const match = _lookupTree<T>(ctx, ctx.root, method, segments, 0);
if (match === undefined) {
return;
}

const [data, paramNames] = match;
if (opts?.ignoreParams || !paramNames) {
return { data };
if (opts?.params || !match.paramsMap) {
return {
data: match.data,
params: undefined,
};
}

const params = _getParams(segments, paramNames);

return {
data,
params,
data: match.data,
params: getMatchParams(segments, match.paramsMap),
};
}

function _lookupTree<T>(
ctx: RouterContext,
ctx: RouterContext<T>,
node: Node<T>,
method: string,
segments: string[],
index: number,
): [Data: T, Params?: Params] | undefined {
// End of path
): MethodData<T> | undefined {
// 0. End of path
if (index === segments.length) {
if (node.methods) {
const match = node.methods[method] || node.methods[""];
Expand Down Expand Up @@ -100,25 +101,3 @@ function _lookupTree<T>(
// No match
return;
}

function _getParams(
segments: string[],
paramsNames: Params,
): MatchedRoute["params"] {
const params = Object.create(null);
for (const [index, name] of paramsNames) {
const segment =
index < 0 ? segments.slice(-1 * index).join("/") : segments[index];
if (typeof name === "string") {
params[name] = segment;
} else {
const match = segment.match(name);
if (match) {
for (const key in match.groups) {
params[key] = match.groups[key];
}
}
}
}
return params;
}
59 changes: 0 additions & 59 deletions src/operations/match.ts

This file was deleted.

7 changes: 4 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ export interface RouterContext<T = unknown> {
static: Record<string, Node<T> | undefined>;
}

export type Params = Array<[Index: number, name: string | RegExp]>;
export type ParamsIndexMap = Array<[Index: number, name: string | RegExp]>;
export type MethodData<T = unknown> = { data: T; paramsMap?: ParamsIndexMap };

export interface Node<T = unknown> {
key: string;
Expand All @@ -13,10 +14,10 @@ export interface Node<T = unknown> {
wildcard?: Node<T>;

index?: number;
methods?: Record<string, [Data: T, Params?: Params] | undefined>;
methods?: Record<string, MethodData<T> | undefined>;
}

export type MatchedRoute<T = unknown> = {
data?: T | undefined;
data: T;
params?: Record<string, string>;
};
Loading