useEntityFetch.ts 1.6 KB

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