diff --git a/package.json b/package.json index c0523e7..ccaf4af 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "route-fn", - "version": "1.1.0", + "version": "1.1.1", "description": "A simple utility function for typesafe urls.", "license": "MIT", "type": "module", diff --git a/src/index.ts b/src/index.ts index ec6809a..0aec2ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,9 +28,13 @@ export function createRouteFn(routes: Routes) { for (const key in params) { if (key === "searchParams") { const searchParams = new URLSearchParams( - params.searchParams as Record + Object.fromEntries( + Object.entries(params.searchParams ?? {}) + .filter(([, value]) => value !== null && value !== undefined) + .map(([key, value]) => [key, value!.toString()]) + ) ) - url += `?${searchParams.toString()}` + url += searchParams.size ? `?${searchParams.toString()}` : "" } else { const param = (params as Record)[key]! url = url.replace(`:${key}`, param) diff --git a/src/types.ts b/src/types.ts index 43959dc..e928822 100644 --- a/src/types.ts +++ b/src/types.ts @@ -60,7 +60,7 @@ export type RouteIdParams = Record< > export type SearchParams = { - searchParams?: Record + searchParams?: Record } export type RouteParams = Prettify< diff --git a/tests/index.test.ts b/tests/index.test.ts index 41a5ba0..7e6619b 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -22,13 +22,27 @@ describe("route-fn", () => { }) it("should return the correct route with search params", async () => { - const route = createRouteFn(["/account", "/user/:id"]) + const route = createRouteFn(["/user/:id"]) + expect(route("/user/:id", { id: 1, searchParams: { page: 0 } })).toBe( + "/user/1?page=0" + ) expect(route("/user/:id", { id: 1, searchParams: { page: 2 } })).toBe( "/user/1?page=2" ) }) + it("should strip null or undefined search params", async () => { + const route = createRouteFn(["/user/:id"]) + + expect(route("/user/:id", { id: 1, searchParams: { page: null } })).toBe( + "/user/1" + ) + expect( + route("/user/:id", { id: 1, searchParams: { page: undefined } }) + ).toBe("/user/1") + }) + it("should show type error when a param is missing", async () => { const route = createRouteFn(["/user/:id/settings/:page"])