useEntityFetch.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {useEntityManager} from "~/composables/data/useEntityManager";
  2. import ApiResource from "~/models/ApiResource";
  3. import type {AssociativeArray, Collection} from "~/types/data";
  4. import type {AsyncData} from "#app";
  5. import type {ComputedRef, Ref} from "vue";
  6. import {v4 as uuid4} from "uuid";
  7. interface useEntityFetchReturnType {
  8. fetch: (model: typeof ApiResource, id: number) => AsyncData<ApiResource, ApiResource | true>,
  9. fetchCollection: (model: typeof ApiResource, parent?: ApiResource | null, query?: Ref<AssociativeArray>) => AsyncData<Collection, any>
  10. // @ts-ignore
  11. getRef: <T extends ApiResource>(model: typeof T, id: Ref<number | null>) => ComputedRef<null | T>
  12. }
  13. // TODO: améliorer le typage des fonctions sur le modèle de getRef
  14. export const useEntityFetch = (lazy: boolean = false): useEntityFetchReturnType => {
  15. const { em } = useEntityManager()
  16. const fetch = (model: typeof ApiResource, id: number) => useAsyncData(
  17. model.entity + '_' + id + '_' + uuid4(),
  18. () => em.fetch(model, id, true),
  19. { lazy }
  20. )
  21. const fetchCollection = (
  22. model: typeof ApiResource,
  23. parent: ApiResource | null = null,
  24. query: Ref<AssociativeArray | null> = ref(null)
  25. ) => useAsyncData(
  26. model.entity + '_many_' + uuid4(),
  27. () => em.fetchCollection(model, parent, query.value ?? undefined),
  28. { lazy }
  29. )
  30. // @ts-ignore
  31. const getRef = <T extends ApiResource>(model: typeof T, id: Ref<number | null>): ComputedRef<T | null> => {
  32. return computed(() => (id.value ? em.find(model, id.value) as T : null))
  33. }
  34. //@ts-ignore
  35. return { fetch, fetchCollection, getRef }
  36. }