sindresorhus/query-string

Making `arrayFormat: 'comma'` symmetric with one-element arrays

finkrer opened this issue · 4 comments

arrayFormat: 'comma' currently doesn't work as expected with arrays of length 1.

I am using query-string to serialize objects and then read them from the query string, both with arrayFormat: 'comma'.

ids: [1, 2, 3] becomes ids=1,2,3, which is parsed as ids: [1, 2, 3] (expected).

ids: [1] becomes ids=1, which is then parsed as ids: 1 (unexpected).

Now, this can be solved easily by using another array format, but it seems that nothing stops arrayFormat: 'comma' from handling these cases properly.

For example, a solution I came up with is to stringify ids: [1] as ids=1,, which would then be read as ids: [1], as expected.

Trailing comma is already used to indicate a null element:

}), 'a=&b=&c=,a,,');

You're better off either using 'bracket-separator' or even just JSON.stringifying the value (especially if you control both sides of the serialization).

The best solution would be to allow defining the types using some kind of schema: #210

Well, I'm not sure my users would appreciate JSON in their address bar, haha. But yes, I did use bracket-separator in the end. The only difference is that it displays empty arrays, so I had to remove them manually with exclude. Calls for skipEmptyArrays, perhaps?

Other than that, my use case was covered. Thanks for making the package!

@finkrer
Could u please give me your solution for this ?

@phuhd-0935 Sure, something like that.

search = queryString.exclude(
      search,
      (_, value) => (Array.isArray(value) && value.length === 0),
      {
        arrayFormat: 'bracket-separator',
        arrayFormatSeparator: ',',
        parseBooleans: true,
        parseNumbers: true,
        skipEmptyString: true,
      }
    )