useEntityFetch.ts 1.5 KB

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