useAp2iRequestService.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import {useAccessProfileStore} from "~/store/profile/access";
  2. import {FetchContext, FetchOptions} from "ohmyfetch";
  3. import {TYPE_ALERT} from "~/types/enum/enums";
  4. import {navigateTo, useRuntimeConfig} from "#app";
  5. import ApiRequestService from "~/services/data/apiRequestService";
  6. import {AssociativeArray} from "~/types/enum/data";
  7. import {Ref} from "@vue/reactivity";
  8. import {usePageStore} from "~/store/page";
  9. import UnauthorizedError from "~/services/error/UnauthorizedError";
  10. /**
  11. * Retourne une instance de ApiRequestService configurée pour interroger l'api Ap2i
  12. *
  13. * @see https://github.com/unjs/ohmyfetch/blob/main/README.md#%EF%B8%8F-create-fetch-with-default-options
  14. */
  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. // $axios.setToken(`${store.state.profile.access.bearer}`, 'Bearer')
  40. pending.value = true
  41. console.log('Request : ' + request + ' (SSR: ' + process.server + ')')
  42. }
  43. const onRequestError = async function({ request, options, response }: FetchContext) {
  44. pending.value = false
  45. }
  46. /**
  47. * Server responded
  48. *
  49. * @param request
  50. * @param options
  51. * @param response
  52. */
  53. const onResponse = async function({ request, options, response }: FetchContext) {
  54. pending.value = false
  55. }
  56. /**
  57. * Gère les erreurs retournées par l'api
  58. *
  59. * @param request
  60. * @param response
  61. * @param error
  62. */
  63. const onResponseError = async function ({ request, response, error }: FetchContext) {
  64. pending.value = false
  65. if (response && response.status === 401) {
  66. throw new UnauthorizedError('Ap2i - Unauthorized')
  67. }
  68. else if (response && response.status === 403) {
  69. usePageStore().addAlerts(TYPE_ALERT.ALERT, ['forbidden'])
  70. console.error('Forbidden')
  71. }
  72. else if (response && response.status >= 404) {
  73. // @see https://developer.mozilla.org/fr/docs/Web/HTTP/Status
  74. usePageStore().addAlerts(TYPE_ALERT.ALERT, [error ? error.message : response.statusText])
  75. console.error(error ? error.message : response.statusText)
  76. }
  77. }
  78. const config : FetchOptions = {
  79. baseURL,
  80. onRequest,
  81. onRequestError,
  82. onResponse,
  83. onResponseError
  84. }
  85. // Utilise la fonction `create` d'ohmyfetch pour générer un fetcher dédié à l'interrogation de Ap2i
  86. const fetcher = $fetch.create(config)
  87. return { apiRequestService: new ApiRequestService(fetcher), pending: pending }
  88. }