Quellcode durchsuchen

revise UrlUtils.extractId

Olivier Massot vor 2 Jahren
Ursprung
Commit
9d4a2cd9cd
2 geänderte Dateien mit 11 neuen und 4 gelöschten Zeilen
  1. 8 4
      services/utils/urlUtils.ts
  2. 3 0
      tests/units/services/utils/urlUtils.test.ts

+ 8 - 4
services/utils/urlUtils.ts

@@ -56,18 +56,22 @@ class UrlUtils {
 
   /**
    * Extrait l'ID de l'URI passée en paramètre
-   * L'URI est supposée être de la forme `.../foo/bar/{id}`, où l'id est un identifiant numérique
+   * L'URI est supposée être de la forme `.../foo/bar/{id}`,
+   * où l'id est un identifiant numérique, à moins que isLiteral soit défini comme vrai.
+   * Dans ce cas, si isLiteral est vrai, l'id sera retourné sous forme de texte.
+   *
    *
    * @param uri
+   * @param isLiteral
    */
-  public static extractIdFromUri (uri: string): number|null {
+  public static extractIdFromUri (uri: string, isLiteral: boolean = false): number|string|null {
     const partUri: Array<string> = uri.split('/')
     const id: any = partUri.pop()
 
-    if (!id || isNaN(id)) {
+    if (!id || (!isLiteral && isNaN(id))) {
       throw new Error('no id found')
     }
-    return parseInt(id)
+    return isLiteral ? id : parseInt(id)
   }
 
   /**

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

@@ -66,6 +66,9 @@ describe('extractIdFromUri', () => {
     test('extract id from uri', () => {
         expect(UrlUtils.extractIdFromUri('/api/organizations/1000')).toEqual(1000)
     })
+    test('try to literal id', () => {
+        expect(UrlUtils.extractIdFromUri('/api/organizations/abc', true)).toEqual('abc')
+    })
     test('try to extract missing id', () => {
         expect(() => UrlUtils.extractIdFromUri('/api/organizations/first')).toThrowError('no id found')
     })