Skip to content

Commit

Permalink
fix(query): filter undefined values in arrays
Browse files Browse the repository at this point in the history
Same behavior as with Vue Router 3
  • Loading branch information
posva committed May 10, 2021
1 parent 885bb06 commit df25fb5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
15 changes: 11 additions & 4 deletions __tests__/stringifyQuery.spec.ts
Expand Up @@ -28,10 +28,17 @@ describe('stringifyQuery', () => {
expect(stringifyQuery({ e: undefined, b: 'a' })).toEqual('b=a')
})

it('ignores undefined and empty arrays', () => {
expect(
stringifyQuery({ a: [undefined, 'b'], b: undefined, c: [] })
).toEqual('a=b')
it('avoids trailing &', () => {
expect(stringifyQuery({ a: 'a', b: undefined })).toEqual('a=a')
expect(stringifyQuery({ a: 'a', c: [] })).toEqual('a=a')
})

it('skips undefined in arrays', () => {
expect(stringifyQuery({ a: [undefined, '3'] })).toEqual('a=3')
expect(stringifyQuery({ a: [1, undefined, '3'] })).toEqual('a=1&a=3')
expect(stringifyQuery({ a: [1, undefined, '3', undefined] })).toEqual(
'a=1&a=3'
)
})

it('stringifies arrays', () => {
Expand Down
25 changes: 16 additions & 9 deletions src/query.ts
@@ -1,13 +1,15 @@
import { decode, encodeQueryKey, encodeQueryValue, PLUS_RE } from './encoding'

/**
* Possible values in normalized {@link LocationQuery}
* Possible values in normalized {@link LocationQuery}. `null` renders the query
* param but without an `=`: `?isNull&isEmpty=&other=other` -> `{ isNull: null,
* isEmpty: '', other: 'other' }`.
*
* @internal
*/
export type LocationQueryValue = string | null
/**
* Possible values when defining a query
* Possible values when defining a query.
*
* @internal
*/
Expand Down Expand Up @@ -93,20 +95,25 @@ export function stringifyQuery(query: LocationQueryRaw): string {
key = encodeQueryKey(key)
if (value == null) {
// only null adds the value
if (value !== undefined) search += (search.length ? '&' : '') + key
if (value !== undefined) {
search += (search.length ? '&' : '') + key
}
continue
}
// keep null values
let values: LocationQueryValueRaw[] = Array.isArray(value)
? value.map(v => v && encodeQueryValue(v))
: [value && encodeQueryValue(value)]

for (let i = 0; i < values.length; i++) {
if (values[i] === undefined) continue
// only append & with non-empty search
search += (search.length ? '&' : '') + key
if (values[i] !== null) search += ('=' + values[i]) as string
}
values.forEach(value => {
// skip undefined values in arrays as if they were not present
// smaller code than using filter
if (value !== undefined) {
// only append & with non-empty search
search += (search.length ? '&' : '') + key
if (value != null) search += '=' + value
}
})
}

return search
Expand Down

0 comments on commit df25fb5

Please sign in to comment.