Переглянути джерело

convert utils classes into literal objects

Olivier Massot 4 місяців тому
батько
коміт
d0a507f3f8

+ 6 - 8
services/utils/arrayUtils.ts

@@ -1,24 +1,20 @@
 import type { AnyJson } from '~/types/data'
 
-export default class ArrayUtils {
-  // Private constructor to prevent instantiation
-  private constructor() {
-    // This utility class is not meant to be instantiated
-  }
+const ArrayUtils = {
   /**
    * Trie un tableau
    *
    * @param array
    * @param reverse
    */
-  public static sort(
+  sort(
     array: Array<object | string | number>,
     reverse: boolean = false,
   ): Array<object | string | number> {
     return array.sort((a, b) => {
       return (a < b ? -1 : a > b ? 1 : 0) * (reverse ? -1 : 1)
     })
-  }
+  },
 
   /**
    * Trie un tableau d'objets selon une propriété commune
@@ -27,7 +23,7 @@ export default class ArrayUtils {
    * @param property Le nom d'une propriété possédée par tous les objets
    * @param reverse
    */
-  public static sortObjectsByProp(
+  sortObjectsByProp(
     array: Array<AnyJson>,
     property: string,
     reverse: boolean = false,
@@ -40,3 +36,5 @@ export default class ArrayUtils {
     })
   }
 }
+
+export default ArrayUtils

+ 16 - 18
services/utils/dateUtils.ts

@@ -10,14 +10,10 @@ export const enum supportedLocales {
 
 const defaultLocale = 'fr'
 
-export default class DateUtils {
-  private constructor() {
-    // Private constructor to prevent instantiation
-    // This utility class is not meant to be instantiated
-  }
-  public static format(date: Date, fmt: string): string {
+const DateUtils = {
+  format(date: Date, fmt: string): string {
     return format(date, fmt)
-  }
+  },
 
   /**
    * Formate la ou les dates au format donné et retourne la liste concaténée
@@ -26,14 +22,14 @@ export default class DateUtils {
    * @param fmt
    * @param sep
    */
-  public static formatAndConcat(
+  formatAndConcat(
     dates: Date | Array<Date>,
     fmt: string,
     sep: string = ' - ',
   ): string {
     dates = Array.isArray(dates) ? dates : [dates]
     return dates.map((d) => this.format(d, fmt)).join(sep)
-  }
+  },
 
   /**
    * Trie les dates par ordre chronologique
@@ -41,39 +37,41 @@ export default class DateUtils {
    * @param dates
    * @param reverse
    */
-  public static sort(
+  sort(
     dates: Array<Date>,
     reverse: boolean = false,
   ): Array<Date> {
     return ArrayUtils.sort(dates, reverse) as Array<Date>
-  }
+  },
 
-  public static getFnsLocale(code: supportedLocales): Locale {
+  getFnsLocale(code: supportedLocales): Locale {
     // noinspection TypeScriptUnresolvedReference
     const mapping = {
       en: enUS,
       fr,
     }
     return mapping[code] ?? mapping[defaultLocale]
-  }
+  },
 
-  public static getShortFormatPattern(code: supportedLocales): string {
+  getShortFormatPattern(code: supportedLocales): string {
     const mapping = {
       en: 'MM/dd/yyyy',
       fr: 'dd/MM/yyyy',
     }
     return mapping[code] ?? mapping[defaultLocale]
-  }
+  },
 
-  public static getFormatPattern(code: supportedLocales): string {
+  getFormatPattern(code: supportedLocales): string {
     const mapping = {
       en: 'MM/dd/yyyy HH:mm',
       fr: 'dd/MM/yyyy HH:mm',
     }
     return mapping[code] ?? mapping[defaultLocale]
-  }
+  },
 
-  public static formatIsoShortDate(date: Date): string {
+  formatIsoShortDate(date: Date): string {
     return format(date, 'yyyy-MM-dd')
   }
 }
+
+export default DateUtils

+ 4 - 8
services/utils/fileUtils.ts

@@ -1,26 +1,22 @@
 /**
  * Manipulation des images
  */
-class FileUtils {
-  // Private constructor to prevent instantiation
-  private constructor() {
-    // This utility class is not meant to be instantiated
-  }
+const FileUtils = {
   /**
    * Returns a blob with the given data and the file's type
    *
    * @param data
    * @param filetype
    */
-  public static newBlob(data: BlobPart, filetype: string = 'image/jpeg'): Blob {
+  newBlob(data: BlobPart, filetype: string = 'image/jpeg'): Blob {
     return new Blob([data], { type: filetype })
-  }
+  },
 
   /**
    * Transforme un Blob en Base64
    * @param {Blob} blob
    */
-  public static blobToBase64(blob: Blob): Promise<string> {
+  blobToBase64(blob: Blob): Promise<string> {
     return new Promise((resolve, _reject) => {
       const reader = new FileReader()
       reader.onloadend = () => resolve(reader.result as string)

+ 17 - 19
services/utils/objectUtils.ts

@@ -1,16 +1,12 @@
 /**
  * @category Services/utils
- * @class ObjectUtils
- * Classe aidant à manipuler des Objets
+ * Utilitaire aidant à manipuler des Objets
  */
 import _ from 'lodash'
 import type { AnyJson } from '~/types/data'
 import StringUtils from '~/services/utils/stringUtils'
-export default class ObjectUtils {
-  // Private constructor to prevent instantiation
-  private constructor() {
-    // This utility class is not meant to be instantiated
-  }
+
+const ObjectUtils = {
   /**
    * Flatten un objet nested en un objet avec un seul niveau avec des noms de propriétés transformées comme cela 'foo.bar'
    * L'objet passé en paramètre reste inchangé car il est cloné
@@ -21,7 +17,7 @@ export default class ObjectUtils {
    * @param excludedProperties
    * @return {AnyJson}
    */
-  static cloneAndFlatten(
+  cloneAndFlatten(
     object: AnyJson,
     excludedProperties: Array<string> = [],
   ): AnyJson {
@@ -53,7 +49,7 @@ export default class ObjectUtils {
       }
       return values
     }, {})
-  }
+  },
 
   /**
    * Transforme un objet flattened en un objet nested. L'objet passé en paramètre reste inchangé
@@ -62,7 +58,7 @@ export default class ObjectUtils {
    * @param {AnyJson} object
    * @return {AnyJson}
    */
-  static cloneAndNest(object: AnyJson): AnyJson {
+  cloneAndNest(object: AnyJson): AnyJson {
     if (typeof object !== 'object') {
       throw new TypeError('Expecting an object parameter')
     }
@@ -94,7 +90,7 @@ export default class ObjectUtils {
         )
       return values
     }, {})
-  }
+  },
 
   /**
    * Teste si le paramètre est un objet
@@ -102,14 +98,14 @@ export default class ObjectUtils {
    * @param {AnyJson} value
    * @return {boolean}
    */
-  static isObject(value: unknown): boolean {
+  isObject(value: unknown): boolean {
     return (
       value !== null &&
       typeof value === 'object' &&
       !Array.isArray(value) &&
-      ObjectUtils.prototype.toString.call(value) !== '[object Date]'
+      Object.prototype.toString.call(value) !== '[object Date]'
     )
-  }
+  },
 
   /**
    * Clone l'objet et ses propriétés.
@@ -117,14 +113,14 @@ export default class ObjectUtils {
    * @param {ObjectUtils} object
    * @return {ObjectUtils}
    */
-  static clone(object: AnyJson): AnyJson {
+  clone(object: AnyJson): AnyJson {
     return Object.keys(object).reduce((values: AnyJson, name: string) => {
       if (Object.prototype.hasOwnProperty.call(object, name)) {
         values[name] = object[name]
       }
       return values
     }, {})
-  }
+  },
 
   /**
    * Trie un objet selon ses clés (par ordre alphanumérique)
@@ -132,7 +128,7 @@ export default class ObjectUtils {
    * @example sortObjectsByKey({b:1, d:2, c:3, a:4}) => {a:4, b:1, c:3, d:2}
    * @param toSort
    */
-  static sortObjectsByKey(toSort: AnyJson): AnyJson {
+  sortObjectsByKey(toSort: AnyJson): AnyJson {
     if (typeof toSort !== 'object') {
       throw new TypeError('Expecting an object parameter')
     }
@@ -142,7 +138,7 @@ export default class ObjectUtils {
         obj[key] = toSort[key]
         return obj
       }, {})
-  }
+  },
 
   /**
    * Créé un hash à partir d'un objet
@@ -150,8 +146,10 @@ export default class ObjectUtils {
    *
    * @param obj
    */
-  static async hash(obj: object): Promise<string> {
+  async hash(obj: object): Promise<string> {
     const sortedObject = this.sortObjectsByKey(_.cloneDeep(obj))
     return await StringUtils.hash(JSON.stringify(sortedObject), 'SHA-1')
   }
 }
+
+export default ObjectUtils

+ 4 - 6
services/utils/refUtils.ts

@@ -1,11 +1,7 @@
 import type { UnwrapRef } from 'vue'
 import { ref, isRef } from 'vue'
 
-export default class RefUtils {
-  // Private constructor to prevent instantiation
-  private constructor() {
-    // This utility class is not meant to be instantiated
-  }
+const RefUtils = {
   /**
    * Convertit la valeur passée en référence.
    * S'il s'agit déjà d'une ref, selon que `maintainReactivity` est vrai ou faux, on conserve la référence existante
@@ -14,7 +10,7 @@ export default class RefUtils {
    * @param value
    * @param maintainReactivity
    */
-  static castToRef<T>(
+  castToRef<T>(
     value: T | Ref<T>,
     maintainReactivity: boolean = true,
   ): Ref<T> | Ref<UnwrapRef<T>> {
@@ -29,3 +25,5 @@ export default class RefUtils {
     }
   }
 }
+
+export default RefUtils

+ 8 - 10
services/utils/stringUtils.ts

@@ -1,16 +1,12 @@
 import crypto from 'crypto'
 
-export default class StringUtils {
-  // Private constructor to prevent instantiation
-  private constructor() {
-    // This utility class is not meant to be instantiated
-  }
+const StringUtils = {
   /**
    * Normalise une chaine de caractères en retirant la casse et les caractères spéciaux, à des fins de recherche
    * par exemple
    * @param s
    */
-  public static normalize(s: string): string {
+  normalize(s: string): string {
     return s
       .toLowerCase()
       .replace(/[éèẽëêēĕėęě]/g, 'e')
@@ -26,16 +22,16 @@ export default class StringUtils {
       .replace(/[ž]/g, 'z')
       .replace(/-/g, ' ')
       .trim()
-  }
+  },
 
   /**
    * Convertit le paramètre d'entrée en entier
    * A la différence de parseInt, cette méthode accepte aussi les nombres.
    * @param s
    */
-  public static parseInt(s: string | number) {
+  parseInt(s: string | number) {
     return typeof s === 'number' ? s : parseInt(s)
-  }
+  },
 
   /**
    * Hash une chaine de caractères avec l'algorithme demandé
@@ -43,7 +39,7 @@ export default class StringUtils {
    * @param input
    * @param algorithm
    */
-  public static async hash(input: string, algorithm: string = 'SHA-256') {
+  async hash(input: string, algorithm: string = 'SHA-256') {
     const textAsBuffer = new TextEncoder().encode(input)
 
     const isNode =
@@ -59,3 +55,5 @@ export default class StringUtils {
     return hashArray.map((item) => item.toString(16).padStart(2, '0')).join('')
   }
 }
+
+export default StringUtils

+ 16 - 16
services/utils/urlUtils.ts

@@ -1,16 +1,16 @@
 import _ from 'lodash'
 
 /**
- * Classe permettant de construire une URL pour l'interrogation d'une API externe
+ * Utilitaire permettant de construire une URL pour l'interrogation d'une API externe
  */
-class UrlUtils {
+const UrlUtils = {
   /**
    * Concatenate a base url and a tail
    * @param base
    * @param tails
    * @private
    */
-  public static join(
+  join(
     base: string | number,
     ...tails: Array<string | number>
   ): string {
@@ -20,19 +20,19 @@ class UrlUtils {
         url.replace(/^|\/$/g, '') + '/' + String(tail).replace(/^\/?|$/g, '')
     })
     return url
-  }
+  },
 
   /**
    * Prepend the 'https://' part if neither 'http://' nor 'https://' prefixes are present, else does nothing
    *
    * @param url
    */
-  public static prependHttps(url: string): string {
+  prependHttps(url: string): string {
     if (!url.match(/^https?:\/\/.*/)) {
       url = 'https://' + url
     }
     return url
-  }
+  },
 
   /**
    * Parse an URI to retrieve a parameter
@@ -42,12 +42,12 @@ class UrlUtils {
    * @param default_
    * @private
    */
-  public static getParameter(
+  getParameter(
     uri: string,
     parameter: string,
     default_: string | number | null = null,
   ): string | number | null {
-    uri = UrlUtils.prependHttps(uri)
+    uri = this.prependHttps(uri)
 
     const urlParams = new URL(uri).searchParams
     let value: string | number | null = urlParams.get(parameter)
@@ -62,7 +62,7 @@ class UrlUtils {
     }
 
     return value ?? default_
-  }
+  },
 
   /**
    * Extrait l'ID de l'URI passée en paramètre
@@ -73,7 +73,7 @@ class UrlUtils {
    * @param uri
    * @param isLiteral
    */
-  public static extractIdFromUri(
+  extractIdFromUri(
     uri: string,
     isLiteral: boolean = false,
   ): number | string | null {
@@ -84,7 +84,7 @@ class UrlUtils {
       throw new Error('no id found')
     }
     return isLiteral ? id : parseInt(id)
-  }
+  },
 
   /**
    * Découpe une URI au niveau des '/'
@@ -99,9 +99,9 @@ class UrlUtils {
    *
    * @param uri
    */
-  public static split(uri: string) {
+  split(uri: string) {
     return uri.split('/').filter((s) => s.length > 0)
-  }
+  },
 
   /**
    * Format and add a query to an url
@@ -116,7 +116,7 @@ class UrlUtils {
    * @param url
    * @param query
    */
-  public static addQuery(url: string | URL, query: object): string {
+  addQuery(url: string | URL, query: object): string {
     let urlObj = new URL(url, 'https://temporary-dommain.inexistent') as URL
 
     if (!_.isEmpty(query)) {
@@ -137,14 +137,14 @@ class UrlUtils {
     }
 
     return result
-  }
+  },
 
   /**
    * Make an ApiPlatform IRI for the given entity and id
    *
    * @see https://api-platform.com/docs/admin/handling-relations/
    */
-  public static makeIRI(entity: string, id: number) {
+  makeIRI(entity: string, id: number) {
     if (!_.isNumber(id)) {
       throw new TypeError('Invalid id : ' + id)
     }