Skip to content

Commit

Permalink
Allow lists in query strings
Browse files Browse the repository at this point in the history
There are use cases where you may want to add an array of values to a
query string. I.E. `ids[]=1&ids[]=2`.

Previously the `mergeEntries` function was simply replacing any item in
the search params with an identical name. This had the effect of only
including the final entry in the params.

This updates the `mergeEntires` function to just do an append rather
than a replace if the entry name contains `[]`.
  • Loading branch information
dphaener committed Oct 18, 2022
1 parent e6d1c01 commit 107ea04
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
8 changes: 8 additions & 0 deletions __tests__/fetch_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,14 @@ describe('query params are parsed', () => {
const urlAndOptionRequest = new FetchRequest("post", "localhost/test", { query: urlSearchParams })
expect(urlAndOptionRequest.url).toBe("localhost/test?a=1")
})
test('urlSearchParams with list entries', () => {
const urlSearchParams = new URLSearchParams()
urlSearchParams.append("a[]", 1)
urlSearchParams.append("a[]", 2)

const urlAndOptionRequest = new FetchRequest("post", "localhost/test", {query: urlSearchParams})
expect(urlAndOptionRequest.url).toBe("localhost/test?a%5B%5D=1&a%5B%5D=2")
});
test('handles empty query', () => {
const emptyQueryRequest = new FetchRequest("get", "localhost/test")
expect(emptyQueryRequest.url).toBe("localhost/test")
Expand Down
1 change: 1 addition & 0 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export function mergeEntries (searchParams, entries) {
if (value instanceof window.File) continue

if (searchParams.has(name)) {
if (searchParams.has(name) && !name.includes('[]')) {
searchParams.delete(name)
searchParams.set(name, value)
} else {
Expand Down

0 comments on commit 107ea04

Please sign in to comment.