useRefreshProfile.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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)) 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(switchId ?? 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. // @ts-expect-error MyProfile extends AccessProfile but type system doesn't recognize compatibility
  41. accessProfileStore.initiateProfile(profile)
  42. organizationProfileStore.initiateProfile(profile.organization)
  43. }
  44. /**
  45. * Re-fetch the user profile and update the store
  46. */
  47. const refreshProfile = async (accessId: number | null = null) => {
  48. const profile = await fetchProfile(accessId)
  49. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  50. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  51. em.flush(MyProfile)
  52. // @ts-expect-error MyProfile extends AccessProfile but type system doesn't recognize compatibility
  53. accessProfileStore.setProfile(profile)
  54. organizationProfileStore.setProfile(profile.organization)
  55. }
  56. return { initiateProfile, refreshProfile }
  57. }