useAp2iRequestService.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. /**
  9. * Retourne une instance de ApiRequestService configurée pour interroger l'api Ap2i
  10. *
  11. * @see https://github.com/unjs/ohmyfetch/blob/main/README.md#%EF%B8%8F-create-fetch-with-default-options
  12. */
  13. let apiRequestServiceClass: null | ApiRequestService = null
  14. export const useAp2iRequestService = () => {
  15. const runtimeConfig = useRuntimeConfig()
  16. const baseURL = runtimeConfig.baseUrl ?? runtimeConfig.public.baseUrl
  17. const pending: Ref<boolean> = ref(false)
  18. /**
  19. * Peuple les headers avant l'envoi de la requête
  20. *
  21. * @param request
  22. * @param options
  23. */
  24. const onRequest = function ({ request, options }: FetchContext) {
  25. // @ts-expect-error options is not aware of noXaccessId
  26. if (options && options.noXaccessId) {
  27. return
  28. }
  29. const accessProfileStore = useAccessProfileStore()
  30. const headers = new Headers(options.headers)
  31. headers.set('x-accessid', String(accessProfileStore.id))
  32. headers.set('Authorization', 'BEARER ' + accessProfileStore.bearer)
  33. if (accessProfileStore.switchId) {
  34. headers.set('x-switch-user', String(accessProfileStore.switchId))
  35. }
  36. options.headers = headers
  37. pending.value = true
  38. console.log('Request : ' + request + ' (SSR: ' + import.meta.server + ')')
  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('Ap2i - 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.push(error.message)
  71. }
  72. else if(response._data && response._data.violations){
  73. for (const violation of response._data.violations) {
  74. errorMsg.push(violation.message as string)
  75. }
  76. }
  77. else if (response._data && response._data.detail) {
  78. errorMsg.push(response._data.detail)
  79. } else if (response.statusText) {
  80. errorMsg.push(response.statusText)
  81. } else {
  82. errorMsg.push('An error occured')
  83. }
  84. console.error('! Request error: ' + errorMsg)
  85. usePageStore().addAlert(TYPE_ALERT.ALERT, errorMsg)
  86. throw ({ response, error })
  87. }
  88. }
  89. const config: FetchOptions = {
  90. baseURL,
  91. onRequest,
  92. onRequestError,
  93. onResponse,
  94. onResponseError,
  95. }
  96. // Utilise la fonction `create` d'ohmyfetch pour générer un fetcher dédié à l'interrogation de Ap2i
  97. const fetcher = $fetch.create(config)
  98. apiRequestServiceClass = new ApiRequestService(fetcher)
  99. return { apiRequestService: apiRequestServiceClass, pending }
  100. }