useApiLegacyRequestService.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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(
  18. runtimeConfig.baseUrlLegacy || runtimeConfig.public.baseUrlLegacy,
  19. 'api',
  20. )
  21. const pending: Ref<boolean> = ref(false)
  22. /**
  23. * Peuple les headers avant l'envoi de la requête
  24. *
  25. * @param request
  26. * @param options
  27. */
  28. const onRequest = function ({ request: _request, options }: FetchContext) {
  29. // @ts-expect-error options is not aware of noXaccessId
  30. if (options && options.noXaccessId) {
  31. return
  32. }
  33. const accessProfileStore = useAccessProfileStore()
  34. const headers = new Headers(options.headers)
  35. headers.set('X-Accessid', String(accessProfileStore.id))
  36. headers.set('Authorization', 'BEARER ' + accessProfileStore.bearer)
  37. if (accessProfileStore.switchId) {
  38. headers.set('X-Switch-Access', String(accessProfileStore.switchId))
  39. }
  40. options.headers = headers
  41. pending.value = true
  42. }
  43. const onRequestError = function (_: FetchContext) {
  44. pending.value = false
  45. }
  46. /**
  47. * Server responded
  48. */
  49. const onResponse = function (_: FetchContext) {
  50. pending.value = false
  51. }
  52. /**
  53. * Gère les erreurs retournées par l'api
  54. *
  55. * @param request
  56. * @param response
  57. * @param error
  58. */
  59. const onResponseError = function ({ response, error }: FetchContext) {
  60. pending.value = false
  61. if (response && response.status === 401) {
  62. throw new UnauthorizedError('Api - Unauthorized')
  63. } else if (response && response.status === 403) {
  64. console.error('! Request error: Forbidden')
  65. usePageStore().addAlert(TYPE_ALERT.ALERT, ['forbidden'])
  66. } else if (
  67. response &&
  68. (response.status === 400 || response.status >= 404)
  69. ) {
  70. // @see https://developer.mozilla.org/fr/docs/Web/HTTP/Status
  71. let errorMsg
  72. if (error) {
  73. errorMsg = error.message
  74. } else if (response._data && response._data.detail) {
  75. errorMsg = response._data.detail
  76. } else if (response.statusText) {
  77. errorMsg = response.statusText
  78. } else {
  79. errorMsg = 'An error occured'
  80. }
  81. console.error('! Request error: ' + errorMsg)
  82. usePageStore().addAlert(TYPE_ALERT.ALERT, [errorMsg])
  83. }
  84. }
  85. const config: FetchOptions = {
  86. baseURL,
  87. onRequest,
  88. onRequestError,
  89. onResponse,
  90. onResponseError,
  91. }
  92. // Avoid memory leak
  93. if (apiRequestServiceClass === null) {
  94. // Utilise la fonction `create` d'ohmyfetch pour générer un fetcher dédié à l'interrogation de Ap2i
  95. const fetcher = $fetch.create(config)
  96. apiRequestServiceClass = new ApiRequestService(fetcher)
  97. }
  98. return { apiRequestService: apiRequestServiceClass, pending }
  99. }