Skip to content

Commit

Permalink
Preserve empty array in query string
Browse files Browse the repository at this point in the history
qs ignores empty array/object and prevents us from sending `?array[]=`.
This is a workaround to map an empty array to `[null]` so it gets treated
as an empty string, and utilize qs `filter` function to map the value.

A regression test was included.

ljharb/qs#362
  • Loading branch information
starsirius committed May 4, 2020
1 parent 02a0f81 commit 45de92a
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,29 @@ export const truncate = (string, length, append = "…") => {
const limit = ~~length
return x.length > limit ? x.slice(0, limit) + append : x
}
export const toQueryString = (options = {}) =>
export const toQueryString = (options = {}) => {
// qs ignores empty array/object and prevents us from sending `?array[]=`.
// This is a workaround to map an empty array to `[null]` so it gets treated
// as an empty string.
// https://github.com/ljharb/qs/issues/362
const mapEmptyArray = a => (Array.isArray(a) && a.length === 0 ? [null] : a)

/**
* In the case of batched requests we want to explicitly _not_ sort the
* params because the order matters to dataloader
*/
// @ts-ignore
options.batched
return options.batched
? stringify(options, {
arrayFormat: "brackets",
filter: (_prefix, v) => mapEmptyArray(v),
})
: stringify(options, {
arrayFormat: "brackets",
sort: (a, b) => a.localeCompare(b),
filter: (_prefix, v) => mapEmptyArray(v),
})
}
export const toKey = (path, options = {}) => `${path}?${toQueryString(options)}`
export const exclude = (values?: any[], property?: any) => xs =>
reject(xs, x => includes(values, x[property]))
Expand Down

0 comments on commit 45de92a

Please sign in to comment.