useAp2iRequestService.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import {TYPE_ALERT} from "~/types/enum/enums";
  2. import ApiRequestService from "~/services/data/apiRequestService";
  3. import type {Ref} from "@vue/reactivity";
  4. import {usePageStore} from "~/stores/page";
  5. import UnauthorizedError from "~/services/error/UnauthorizedError";
  6. import {useAccessProfileStore} from "~/stores/accessProfile";
  7. import type {AssociativeArray} from "~/types/data";
  8. import type {FetchContext, FetchOptions} from "ofetch";
  9. /**
  10. * Retourne une instance de ApiRequestService configurée pour interroger l'api Ap2i
  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 useAp2iRequestService = () => {
  16. const runtimeConfig = useRuntimeConfig()
  17. const baseURL = runtimeConfig.baseUrl ?? runtimeConfig.public.baseUrl
  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 = async function ({ request, options }: FetchContext) {
  26. // @ts-ignore
  27. if(options && options.noXaccessId) {
  28. return
  29. }
  30. const accessProfileStore = useAccessProfileStore()
  31. const headers: AssociativeArray = {
  32. 'x-accessid': String(accessProfileStore.id),
  33. 'Authorization': 'BEARER ' + accessProfileStore.bearer,
  34. }
  35. if (accessProfileStore.switchId) {
  36. headers['x-switch-user'] = String(accessProfileStore.switchId)
  37. }
  38. options.headers = { ...options.headers, ...headers }
  39. pending.value = true
  40. console.log('Request : ' + request + ' (SSR: ' + process.server + ')')
  41. }
  42. const onRequestError = async function({ request, options, response }: FetchContext) {
  43. pending.value = false
  44. }
  45. /**
  46. * Server responded
  47. *
  48. * @param request
  49. * @param options
  50. * @param response
  51. */
  52. const onResponse = async function({ request, options, response }: FetchContext) {
  53. pending.value = false
  54. }
  55. /**
  56. * Gère les erreurs retournées par l'api
  57. *
  58. * @param request
  59. * @param response
  60. * @param error
  61. */
  62. const onResponseError = async function ({ request, response, error }: FetchContext) {
  63. pending.value = false
  64. if (response && response.status === 401) {
  65. throw new UnauthorizedError('Ap2i - Unauthorized')
  66. }
  67. else if (response && response.status === 403) {
  68. console.error('! Request error: Forbidden')
  69. usePageStore().addAlert(TYPE_ALERT.ALERT, ['forbidden'])
  70. }
  71. else if (response && (response.status === 400 || response.status >= 404)) {
  72. // @see https://developer.mozilla.org/fr/docs/Web/HTTP/Status
  73. const error_msg = error ? error.message : response.statusText
  74. console.error('! Request error: ' + error_msg)
  75. usePageStore().addAlert(TYPE_ALERT.ALERT, [error_msg])
  76. }
  77. }
  78. const config : FetchOptions = {
  79. baseURL,
  80. onRequest,
  81. onRequestError,
  82. onResponse,
  83. onResponseError
  84. }
  85. //Avoid memory leak
  86. if (apiRequestServiceClass === null) {
  87. // Utilise la fonction `create` d'ohmyfetch pour générer un fetcher dédié à l'interrogation de Ap2i
  88. const fetcher = $fetch.create(config)
  89. // @ts-ignore
  90. apiRequestServiceClass = new ApiRequestService(fetcher)
  91. }
  92. return { apiRequestService: apiRequestServiceClass, pending: pending }
  93. }