]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix(query): prevent trailing & in query (#935)
authorArtyom Tuchkov <throwget@gmail.com>
Mon, 10 May 2021 09:49:52 +0000 (12:49 +0300)
committerGitHub <noreply@github.com>
Mon, 10 May 2021 09:49:52 +0000 (11:49 +0200)
* fix(query): `&` sign doesn't remove properly

* test: improve title and remove unnecessary test case

__tests__/stringifyQuery.spec.ts
src/query.ts

index c39d1b4e8dfe458599067a099b6055e4d865ddbd..fc6604eb508b984410da854ad00991fd794b0f2d 100644 (file)
@@ -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')
   })
index c936c7a2704e01d7418327a92cf7f5a303428c2e..b32ba105d991c0a4f6ef38ce9d9bc8271ffa5e7f 100644 (file)
@@ -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
     }
   }