useApiLegacyRequestService.ts 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import type { Ref } from 'vue'
  2. import type { FetchContext, FetchOptions } from 'ofetch'
  3. import { TYPE_ALERT } from '~/types/enum/enums'
  4. import ApiRequestService from '~/services/data/apiRequestService'
  5. import { usePageStore } from '~/stores/page'
  6. import UnauthorizedError from '~/services/error/UnauthorizedError'
  7. import { useAccessProfileStore } from '~/stores/accessProfile'
  8. import UrlUtils from "~/services/utils/urlUtils";
  9. /**
  10. * Retourne une instance de ApiRequestService configurée pour interroger l'api legacy
  11. *
  12. * @see https://github.com/unjs/ohmyfetch/blob/main/README.md#%EF%B8%8F-create-fetch-with-default-options
  13. */
  14. let apiRequestServiceClass: null | ApiRequestService = null
  15. export const useApiLegacyRequestService = () => {
  16. const runtimeConfig = useRuntimeConfig()
  17. const baseURL = UrlUtils.join(runtimeConfig.baseUrlLegacy || runtimeConfig.public.baseUrlLegacy, 'api')
  18. const pending: Ref<boolean> = ref(false)
  19. /**
  20. * Peuple les headers avant l'envoi de la requête
  21. *
  22. * @param request
  23. * @param options
  24. */
  25. const onRequest = function ({ request, options }: FetchContext) {
  26. // @ts-expect-error options is not aware of noXaccessId
  27. if (options && options.noXaccessId) {
  28. return
  29. }
  30. const accessProfileStore = useAccessProfileStore()
  31. const headers = new Headers(options.headers)
  32. headers.set('X-Accessid', String(accessProfileStore.id))
  33. headers.set('Authorization', 'BEARER ' + accessProfileStore.bearer)
  34. if (accessProfileStore.switchId) {
  35. headers.set('X-Switch-Access', String(accessProfileStore.switchId))
  36. }
  37. options.headers = headers
  38. pending.value = true
  39. }
  40. const onRequestError = function (_: FetchContext) {
  41. pending.value = false
  42. }
  43. /**
  44. * Server responded
  45. */
  46. const onResponse = function (_: FetchContext) {
  47. pending.value = false
  48. }
  49. /**
  50. * Gère les erreurs retournées par l'api
  51. *
  52. * @param request
  53. * @param response
  54. * @param error
  55. */
  56. const onResponseError = function ({ response, error }: FetchContext) {
  57. pending.value = false
  58. if (response && response.status === 401) {
  59. throw new UnauthorizedError('Api - Unauthorized')
  60. } else if (response && response.status === 403) {
  61. console.error('! Request error: Forbidden')
  62. usePageStore().addAlert(TYPE_ALERT.ALERT, ['forbidden'])
  63. } else if (
  64. response &&
  65. (response.status === 400 || response.status >= 404)
  66. ) {
  67. // @see https://developer.mozilla.org/fr/docs/Web/HTTP/Status
  68. let errorMsg
  69. if (error) {
  70. errorMsg = error.message
  71. } else if (response._data && response._data.detail) {
  72. errorMsg = response._data.detail
  73. } else if (response.statusText) {
  74. errorMsg = response.statusText
  75. } else {
  76. errorMsg = 'An error occured'
  77. }
  78. console.error('! Request error: ' + errorMsg)
  79. usePageStore().addAlert(TYPE_ALERT.ALERT, [errorMsg])
  80. }
  81. }
  82. const config: FetchOptions = {
  83. baseURL,
  84. onRequest,
  85. onRequestError,
  86. onResponse,
  87. onResponseError,
  88. }
  89. // Avoid memory leak
  90. if (apiRequestServiceClass === null) {
  91. // Utilise la fonction `create` d'ohmyfetch pour générer un fetcher dédié à l'interrogation de Ap2i
  92. const fetcher = $fetch.create(config)
  93. apiRequestServiceClass = new ApiRequestService(fetcher)
  94. }
  95. return { apiRequestService: apiRequestServiceClass, pending }
  96. }