url.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Classe permettant de construire une URL pour l'interrogation d'une API externe
  3. */
  4. class Url {
  5. /**
  6. * Concatenate a base url and a tail
  7. * @param base
  8. * @param tails
  9. * @private
  10. */
  11. public static join (base: string|number, ...tails: Array<string|number>): string {
  12. let url = String(base)
  13. tails.forEach((tail: string|number) => {
  14. url = url.replace(/^|\/$/g, '') + '/' + String(tail).replace(/^\/?|$/g, '')
  15. })
  16. return url
  17. }
  18. /**
  19. * Prepend the 'https://' part if neither 'http://' of 'https://' is present, else: does nothing
  20. *
  21. * @param url
  22. */
  23. public static prependHttps (url: string): string {
  24. if (!url.match(/^https?:\/\/.*/)) {
  25. url = 'https://' + url;
  26. }
  27. return url;
  28. }
  29. /**
  30. * Parse an URI to retrieve the page number
  31. *
  32. * @param uri
  33. * @param parameter
  34. * @param default_
  35. * @private
  36. */
  37. public static getParameter(
  38. uri: string,
  39. parameter: string,
  40. default_: string | null = null
  41. ): string | null {
  42. const urlParams = new URL(uri).searchParams;
  43. const res = urlParams.get('page');
  44. return res ?? default_
  45. }
  46. /**
  47. * Extrait l'ID de l'URI passée en paramètre
  48. * L'uri est supposée être de la forme `.../foo/bar/{id}`, où l'id est un identifiant numérique
  49. *
  50. * @param uri
  51. */
  52. public static extractIdFromUri (uri: string): number|null {
  53. const partUri: Array<string> = uri.split('/')
  54. const id:any = partUri.pop()
  55. if(isNaN(id))
  56. throw new Error('id is not a number')
  57. return parseInt(id)
  58. }
  59. /**
  60. * Découpe une URI au niveau des '/'
  61. * Utilisé entre autres pour le breadcrumb
  62. *
  63. * Ex:
  64. *
  65. * foo/bar/1 => ['foo', 'bar', '1']
  66. * /foo/bar/1 => ['foo', 'bar', '1']
  67. * https://domain.com/foo/bar/1 => ['https:', 'domain.com', 'foo', 'bar', '1']
  68. *
  69. *
  70. * @param uri
  71. */
  72. public static split(uri: string) {
  73. return uri.split('/').filter((s) => s.length > 0)
  74. }
  75. }
  76. export default Url