From 885bb06bb590944f2e58176151f7b7a6acbc1b4e Mon Sep 17 00:00:00 2001 From: Artyom Tuchkov Date: Mon, 10 May 2021 12:49:52 +0300 Subject: [PATCH] fix(query): prevent trailing & in query (#935) * fix(query): `&` sign doesn't remove properly * test: improve title and remove unnecessary test case --- __tests__/stringifyQuery.spec.ts | 6 ++++++ src/query.ts | 10 +++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/__tests__/stringifyQuery.spec.ts b/__tests__/stringifyQuery.spec.ts index c39d1b4e8..fc6604eb5 100644 --- a/__tests__/stringifyQuery.spec.ts +++ b/__tests__/stringifyQuery.spec.ts @@ -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') }) diff --git a/src/query.ts b/src/query.ts index c936c7a27..b32ba105d 100644 --- a/src/query.ts +++ b/src/query.ts @@ -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 @@ -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 } }