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

fix(router): fallback for method-shadowed routes #461

Merged
merged 8 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
33 changes: 31 additions & 2 deletions src/router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { createRouter as _createRouter } from "radix3";
import {
createRouter as _createRouter,
toRouteMatcher,
RouteMatcher,
} from "radix3";
import type { HTTPMethod, EventHandler } from "./types";
import { createError } from "./error";
import { eventHandler, toEventHandler } from "./event";
Expand Down Expand Up @@ -44,6 +48,9 @@ export function createRouter(opts: CreateRouterOptions = {}): Router {
const _router = _createRouter<RouteNode>({});
const routes: Record<string, RouteNode> = {};

let _matcher: RouteMatcher | undefined;
const _shadowedRoutes: Record<string, EventHandler> = {};

const router: Router = {} as Router;

// Utilities to add a new route
Expand Down Expand Up @@ -100,7 +107,29 @@ export function createRouter(opts: CreateRouterOptions = {}): Router {
const method = (
event.node.req.method || "get"
).toLowerCase() as RouterMethod;
const handler = matched.handlers[method] || matched.handlers.all;

let handler: EventHandler | undefined =
matched.handlers[method] ||
matched.handlers.all ||
_shadowedRoutes[`${path}?${method}`];

// Fallback to search for shadowed routes
if (!handler) {
if (!_matcher) {
_matcher = toRouteMatcher(_router);
}
// Default order is less specific to most specific
const _matches = _matcher.matchAll(path).reverse() as RouteNode[];
for (const _match of _matches) {
handler = _match.handlers[method] || _match.handlers.all;
if (handler) {
_shadowedRoutes[`${path}?${method}`] = handler;
break;
}
}
}

// Method not matched
if (!handler) {
if (opts.preemptive || opts.preemtive) {
throw createError({
Expand Down
23 changes: 23 additions & 0 deletions test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,29 @@ describe("router", () => {
const res = await request.get("/404");
expect(res.status).toEqual(404);
});

it("Handle shadowed route", async () => {
router.post(
"/test/123",
eventHandler((event) => `[${event.method}] ${event.path}`)
);

router.use(
"/test/**",
pi0 marked this conversation as resolved.
Show resolved Hide resolved
eventHandler((event) => `[${event.method}] ${event.path}`)
);

// Loop to validate cached behavior
for (let i = 0; i < 5; i++) {
const postRed = await request.post("/test/123");
expect(postRed.status).toEqual(200);
expect(postRed.text).toEqual("[POST] /test/123");

const getRes = await request.get("/test/123");
expect(getRes.status).toEqual(200);
expect(getRes.text).toEqual("[GET] /test/123");
}
});
});

describe("router (preemptive)", () => {
Expand Down