From 107ea044e5c24381e1bd0781aa1268897e724469 Mon Sep 17 00:00:00 2001 From: Darin Haener Date: Mon, 17 Oct 2022 19:46:24 -0700 Subject: [PATCH] Allow lists in query strings 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 `[]`. --- __tests__/fetch_request.js | 8 ++++++++ src/lib/utils.js | 1 + 2 files changed, 9 insertions(+) diff --git a/__tests__/fetch_request.js b/__tests__/fetch_request.js index 38a1df9..8fdf76d 100644 --- a/__tests__/fetch_request.js +++ b/__tests__/fetch_request.js @@ -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") diff --git a/src/lib/utils.js b/src/lib/utils.js index ec127c1..a326abd 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -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 {