From f0b75b68904cdb2e86446358b70a9ec8b1be1978 Mon Sep 17 00:00:00 2001 From: Russell Briggs Date: Mon, 5 Jul 2021 20:45:16 +0100 Subject: [PATCH] [IMP] router: allow query string in paths --- src/router/router.ts | 8 +++++++- tests/router/router.test.ts | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/router/router.ts b/src/router/router.ts index 5a09838b..47931a36 100644 --- a/src/router/router.ts +++ b/src/router/router.ts @@ -125,7 +125,10 @@ export class Router { const initialParams = this.currentParams; const result = await this.matchAndApplyRules(path); if (result.type === "match") { - const finalPath = this.routeToPath(result.route, result.params); + let finalPath = this.routeToPath(result.route, result.params); + if (path.indexOf("?") > -1) { + finalPath += "?" + path.split("?")[1]; + } const isPopStateEvent = ev && ev instanceof PopStateEvent; if (!isPopStateEvent) { this.setUrlFromPath(finalPath); @@ -239,6 +242,9 @@ export class Router { if (route.path === "*") { return {}; } + if (path.indexOf("?") > -1) { + path = path.split("?")[0]; + } if (path.startsWith("#")) { path = path.slice(1); } diff --git a/tests/router/router.test.ts b/tests/router/router.test.ts index ad0ad6c3..b71df52a 100644 --- a/tests/router/router.test.ts +++ b/tests/router/router.test.ts @@ -60,6 +60,13 @@ describe("router miscellaneous", () => { await router.navigate({ to: "users", params: { id: 3 } }); expect(window.location.href).toBe("http://localhost/test.html#/users/3"); }); + + test("navigate using path and query string should preserve query string", async () => { + router = new TestRouter(env, [{ name: "users", path: "/users/{{id}}" }]); + await router.navigate({ path: "/users/3?test=1" }); + expect(window.location.pathname).toBe("/users/3"); + expect(window.location.search).toBe("?test=1"); + }); }); describe("routeToPath", () => { @@ -117,6 +124,11 @@ describe("getRouteParams", () => { expect(getRouteParams({ path: "*" }, "somepath")).toEqual({}); }); + test("properly match routes with query params", () => { + expect(getRouteParams({ path: "/home" }, "/home?test=1")).toEqual({}); + expect(getRouteParams({ path: "/home" }, "/home?test1=1&test2=2")).toEqual({}); + }); + test("properly match simple routes, mode hash", () => { // simple route expect(getRouteParams({ path: "/home" }, "#/home")).toEqual({});