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(router): expose event.context.matchedRoute #500

Merged
merged 9 commits into from
Aug 8, 2023
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ H3 has a concept of composable utilities that accept `event` (from `eventHandler
- `getQuery(event)`
- `getValidatedBody(event, validate)`
- `getRouterParams(event)`
- `getRouterParam(event, name)`
- `getRouterMatchedPath(event)`
- `getMethod(event, default?)`
- `isMethod(event, expected, allowHead?)`
- `assertMethod(event, expected, allowHead?)`
Expand Down
7 changes: 6 additions & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface Router extends AddRouteShortcuts {

interface RouteNode {
handlers: Partial<Record<RouterMethod | "all", EventHandler>>;
path: string;
}

export interface CreateRouterOptions {
Expand All @@ -60,7 +61,7 @@ export function createRouter(opts: CreateRouterOptions = {}): Router {
) => {
let route = routes[path];
if (!route) {
routes[path] = route = { handlers: {} };
routes[path] = route = { handlers: {}, path };
pi0 marked this conversation as resolved.
Show resolved Hide resolved
_router.insert(path, route);
}
if (Array.isArray(method)) {
Expand Down Expand Up @@ -148,6 +149,10 @@ export function createRouter(opts: CreateRouterOptions = {}): Router {
const params = matched.params || {};
event.context.params = params;

// Add matched path
const matchedPath = matched.path || "/";
pi0 marked this conversation as resolved.
Show resolved Hide resolved
event.context.matchedPath = matchedPath;

// Call handler
return Promise.resolve(handler(event)).then((res) => {
if (res === undefined && (opts.preemptive || opts.preemtive)) {
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export interface H3EventContext extends Record<string, any> {
params?: Record<string, string>;
/* Cached session data */
sessions?: Record<string, Session>;
/* Matched router path */
path?: string;
}

export type EventHandlerResponse<T = any> = T | Promise<T>;
Expand Down
6 changes: 6 additions & 0 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export function getRouterParam(
return params[name];
}

export function getRouterMatchedPath(
event: H3Event,
): NonNullable<H3Event["context"]["matchedPath"]> {
return event.context.matchedPath;
}

/**
* @deprecated Directly use `event.method` instead.
*/
Expand Down
42 changes: 42 additions & 0 deletions test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Router,
getRouterParams,
getRouterParam,
getRouterMatchedPath,
toNodeListener,
eventHandler,
} from "../src";
Expand Down Expand Up @@ -247,3 +248,44 @@ describe("getRouterParam", () => {
});
});
});

describe("getMatchedPath", () => {
let app: App;
let request: SuperTest<Test>;

beforeEach(() => {
app = createApp({ debug: false });
request = supertest(toNodeListener(app));
});

describe("with router", () => {
it("can return the matched path", async () => {
const router = createRouter().get(
"/test/:template",
eventHandler((event) => {
expect(getRouterMatchedPath(event)).toEqual("/test/:template");
return "200";
}),
);
app.use(router);
const result = await request.get("/test/path");

expect(result.text).toBe("200");
});
});

describe("without router", () => {
it("can return `undefined` for matched path", async () => {
app.use(
"/",
eventHandler((event) => {
expect(getRouterMatchedPath(event)).toEqual(undefined);
return "200";
}),
);
const result = await request.get("/test/path");

expect(result.text).toBe("200");
});
});
});