useRefreshProfile.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { useEntityManager } from '~/composables/data/useEntityManager'
  2. import MyProfile from '~/models/Access/MyProfile'
  3. import { useAccessProfileStore } from '~/stores/accessProfile'
  4. import { useOrganizationProfileStore } from '~/stores/organizationProfile'
  5. export const useRefreshProfile = () => {
  6. const accessProfileStore = useAccessProfileStore()
  7. const organizationProfileStore = useOrganizationProfileStore()
  8. const { em } = useEntityManager()
  9. const fetchProfile = async (
  10. accessId: number | null = null,
  11. ): Promise<MyProfile> => {
  12. if (accessId === null) {
  13. accessId = accessProfileStore.currentAccessId
  14. }
  15. return (await em.fetch(MyProfile, accessId, true)) as MyProfile
  16. }
  17. /**
  18. * Fetch the access profile and initiate the user profile and organization profile stores
  19. *
  20. * /!\ Server side only!
  21. *
  22. * @param accessId
  23. * @param bearer
  24. * @param switchId
  25. */
  26. const initiateProfile = async (
  27. accessId: number,
  28. bearer: string,
  29. switchId: number | null,
  30. ): Promise<void> => {
  31. accessProfileStore.$patch({
  32. bearer,
  33. id: accessId,
  34. switchId,
  35. })
  36. const profile = await fetchProfile(accessId)
  37. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  38. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  39. em.flush(MyProfile)
  40. accessProfileStore.initiateProfile(profile)
  41. organizationProfileStore.initiateProfile(profile.organization)
  42. }
  43. /**
  44. * Re-fetch the user profile and update the store
  45. */
  46. const refreshProfile = async (accessId: number | null = null) => {
  47. const profile = await fetchProfile(accessId)
  48. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  49. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  50. em.flush(MyProfile)
  51. accessProfileStore.setProfile(profile)
  52. organizationProfileStore.setProfile(profile.organization)
  53. }
  54. return { initiateProfile, refreshProfile }
  55. }