Skip to content

Commit

Permalink
🐛 Query addon should strip undefined values
Browse files Browse the repository at this point in the history
Should solve #148
  • Loading branch information
elbywan committed Oct 15, 2022
1 parent 6043c75 commit ce395b5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/addons/queryString.ts
@@ -1,5 +1,9 @@
import type { Wretch, Config, WretchAddon } from "../types.js"

function stringify(value?: string | null): string | null {
return typeof value !== "undefined" ? value : ""
}

const appendQueryParams = (url: string, qp: object | string, replace: boolean, config: Config) => {
let queryString: string

Expand All @@ -8,11 +12,12 @@ const appendQueryParams = (url: string, qp: object | string, replace: boolean, c
} else {
const usp = config.polyfill("URLSearchParams", true, true)
for (const key in qp) {
const value = qp[key]
if (qp[key] instanceof Array) {
for (const val of qp[key])
usp.append(key, val)
for (const val of value)
usp.append(key, stringify(val))
} else {
usp.append(key, qp[key])
usp.append(key, stringify(value))
}
}
queryString = usp.toString()
Expand Down
6 changes: 6 additions & 0 deletions test/node/wretch.spec.ts
Expand Up @@ -663,6 +663,12 @@ describe("Wretch", function () {
expect(w.query({}, true)._url).toBe(_URL)
expect(w.query({ a: 1 }).query({}, true)._url).toBe(_URL)
})

it("should strip undefined values", function () {
const w = wretch(_URL).addon(QueryStringAddon)
expect(w.query({ a: undefined, b: 1 })._url).toBe(_URL + "?a=&b=1")
expect(w.query({ array: ["a", "b", undefined, "c"] })._url).toBe(_URL + "?array=a&array=b&array=&array=c")
})
})

describe("Mix", function () {
Expand Down

0 comments on commit ce395b5

Please sign in to comment.