Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(query): prevent trailing & in query (#935)
* fix(query): `&` sign doesn't remove properly

* test: improve title and remove unnecessary test case
  • Loading branch information
mattersj committed May 10, 2021
1 parent 477d673 commit 885bb06
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
6 changes: 6 additions & 0 deletions __tests__/stringifyQuery.spec.ts
Expand Up @@ -28,6 +28,12 @@ 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('stringifies arrays', () => {
expect(stringifyQuery({ e: ['b', 'a'] })).toEqual('e=b&e=a')
})
Expand Down
10 changes: 5 additions & 5 deletions src/query.ts
Expand Up @@ -89,12 +89,11 @@ export function parseQuery(search: string): LocationQuery {
export function stringifyQuery(query: LocationQueryRaw): string {
let search = ''
for (let key in query) {
if (search.length) search += '&'
const value = query[key]
key = encodeQueryKey(key)
if (value == null) {
// only null adds the value
if (value !== undefined) search += key
if (value !== undefined) search += (search.length ? '&' : '') + key
continue
}
// keep null values
Expand All @@ -103,9 +102,10 @@ export function stringifyQuery(query: LocationQueryRaw): string {
: [value && encodeQueryValue(value)]

for (let i = 0; i < values.length; i++) {
// only append & with i > 0
search += (i ? '&' : '') + key
if (values[i] != null) search += ('=' + values[i]) as string
if (values[i] === undefined) continue
// only append & with non-empty search
search += (search.length ? '&' : '') + key
if (values[i] !== null) search += ('=' + values[i]) as string
}
}

Expand Down

0 comments on commit 885bb06

Please sign in to comment.