useEntityFetch.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 = (model: typeof ApiResource, parent: ApiResource | null = null, query: Ref<AssociativeArray | null> = ref(null)) => useAsyncData(
  22. model.entity + '_many_' + uuid4(),
  23. () => em.fetchCollection(model, parent, query.value),
  24. { lazy }
  25. )
  26. // @ts-ignore
  27. const getRef = <T extends ApiResource>(model: typeof T, id: Ref<number | null>): ComputedRef<T | null> => {
  28. return computed(() => (id.value ? em.find(model, id.value) as T : null))
  29. }
  30. //@ts-ignore
  31. return { fetch, fetchCollection, getRef }
  32. }