useRefreshProfile.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 (accessId: number | null = null): Promise<MyProfile> => {
  10. if (accessId === null) {
  11. accessId = accessProfileStore.currentAccessId
  12. }
  13. return await em.fetch(MyProfile, accessId, true) as MyProfile
  14. }
  15. /**
  16. * Fetch the access profile and initiate the user profile and organization profile stores
  17. *
  18. * /!\ Server side only!
  19. *
  20. * @param accessId
  21. * @param bearer
  22. * @param switchId
  23. */
  24. const initiateProfile = async (accessId: number, bearer: string, switchId: number | null): Promise<void> => {
  25. accessProfileStore.$patch({
  26. bearer: bearer,
  27. id: accessId,
  28. switchId: switchId
  29. })
  30. const profile = await fetchProfile(accessId)
  31. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  32. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  33. em.flush(MyProfile)
  34. accessProfileStore.initiateProfile(profile)
  35. organizationProfileStore.initiateProfile(profile.organization)
  36. }
  37. /**
  38. * Re-fetch the user profile and update the store
  39. */
  40. const refreshProfile = async (accessId: number | null = null) => {
  41. const profile = await fetchProfile(accessId)
  42. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  43. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  44. em.flush(MyProfile)
  45. accessProfileStore.setProfile(profile)
  46. organizationProfileStore.setProfile(profile.organization)
  47. }
  48. return { initiateProfile, refreshProfile }
  49. }