Explorar el Código

add UrlUtils.addQuery method

Olivier Massot hace 2 años
padre
commit
bd7ad22072
Se han modificado 2 ficheros con 64 adiciones y 0 borrados
  1. 37 0
      services/utils/urlUtils.ts
  2. 27 0
      tests/units/services/utils/urlUtils.test.ts

+ 37 - 0
services/utils/urlUtils.ts

@@ -1,3 +1,5 @@
+import _ from "lodash";
+
 /**
  * Classe permettant de construire une URL pour l'interrogation d'une API externe
  */
@@ -90,6 +92,41 @@ class UrlUtils {
   public static split(uri: string) {
     return uri.split('/').filter((s) => s.length > 0)
   }
+
+  /**
+   * Format and add a query to an url
+   * If the url already has a query, append the new parameters to it.
+   * If the query is an empty object, does nothing.
+   *
+   * Ex:
+   *     addQuery('foo/bar', {})  =>  'foo/bar'
+   *     addQuery('foo/bar', {'a': 1})  =>  'foo/bar?a=1'
+   *     addQuery('foo/bar?a=1', {'b': 2})  =>  'foo/bar?a=1&b=2'
+   *
+   * @param url
+   * @param query
+   */
+  public static addQuery(url: string | URL, query: object): string {
+
+    let urlObj = new URL(url, 'https://temporary-dommain.inexistent') as URL
+
+    if (!_.isEmpty(query)) {
+      urlObj = new URL(
+          `${urlObj.origin}${urlObj.pathname}${urlObj.hash}?${new URLSearchParams([
+            ...Array.from(urlObj.searchParams.entries()),
+            ...Object.entries(query),
+          ])}`
+      )
+    }
+
+    let result = urlObj.toString()
+
+    if (urlObj.host === 'temporary-dommain.inexistent') {
+      result = result.replace('https://temporary-dommain.inexistent', '')
+    }
+
+    return result
+  }
 }
 
 export default UrlUtils

+ 27 - 0
tests/units/services/utils/urlUtils.test.ts

@@ -91,3 +91,30 @@ describe('split', () => {
         expect(UrlUtils.split('')).toEqual([])
     })
 })
+
+describe('addQuery', () => {
+    test('with empty query', () => {
+        expect(UrlUtils.addQuery('foo/bar', {})).toEqual('/foo/bar')
+    })
+    test('with simple query', () => {
+        expect(UrlUtils.addQuery('foo/bar', {'a': 1})).toEqual('/foo/bar?a=1')
+    })
+    test('with longer query', () => {
+        expect(UrlUtils.addQuery('foo/bar', {'a': 1, 'b': 2})).toEqual('/foo/bar?a=1&b=2')
+    })
+    test('with existing query', () => {
+        expect(UrlUtils.addQuery('foo/bar?a=1', {'b': 2})).toEqual('/foo/bar?a=1&b=2')
+    })
+    test('with empty url', () => {
+        expect(UrlUtils.addQuery('', {'a': 1})).toEqual('/?a=1')
+    })
+    test('with empty url and empty query', () => {
+        expect(UrlUtils.addQuery('', {})).toEqual('/')
+    })
+    test('with absolute url', () => {
+        expect(UrlUtils.addQuery('https://foo.com/bar/', {'a': 1})).toEqual('https://foo.com/bar/?a=1')
+    })
+    test('with number sign in path name', () => {
+        expect(UrlUtils.addQuery('https://foo.com/#/bar/', {'a': 1})).toEqual('https://foo.com/#/bar/?a=1')
+    })
+})