Skip to content

Commit

Permalink
allow for null or undefined search params
Browse files Browse the repository at this point in the history
  • Loading branch information
mattiaz9 committed Apr 28, 2024
1 parent 5532331 commit 35ed9b1
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ export function createRouteFn<const Routes extends string[]>(routes: Routes) {
for (const key in params) {
if (key === "searchParams") {
const searchParams = new URLSearchParams(
params.searchParams as Record<string, string>
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<string, string>)[key]!
url = url.replace(`:${key}`, param)
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export type RouteIdParams<Id extends string> = Record<
>

export type SearchParams = {
searchParams?: Record<string, string | number>
searchParams?: Record<string, string | number | null | undefined>
}

export type RouteParams<Id extends string> = Prettify<
Expand Down
16 changes: 15 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"])

Expand Down

0 comments on commit 35ed9b1

Please sign in to comment.