useEntityFetch.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. import {v4 as uuid4} from "uuid";
  7. interface useEntityFetchReturnType {
  8. fetch: (model: typeof ApiResource, id: number, key?: string | null) => AsyncData<ApiResource, ApiResource | true>,
  9. fetchCollection: (model: typeof ApiResource, parent?: ApiResource | null, query?: Ref<AssociativeArray>, key?: string | null) => 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, key: string | null = null) => useAsyncData(
  17. key ?? (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. key: string | null = null
  26. ) => useAsyncData(
  27. key ?? (model.entity + '_many_' + uuid4()),
  28. () => em.fetchCollection(model, parent, query.value),
  29. { lazy }
  30. )
  31. // @ts-ignore
  32. const getRef = <T extends ApiResource>(model: typeof T, id: Ref<number | null>): ComputedRef<T | null> => {
  33. return computed(() => (id.value ? em.find(model, id.value) as T : null))
  34. }
  35. //@ts-ignore
  36. return { fetch, fetchCollection, getRef }
  37. }