| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import type { AsyncData } from '#app'
- import type { ComputedRef, Ref } from 'vue'
- import { v4 as uuid4 } from 'uuid'
- import type {
- AsyncDataExecuteOptions,
- AsyncDataRequestStatus,
- } from '#app/composables/asyncData'
- import { useEntityManager } from '~/composables/data/useEntityManager'
- import type ApiResource from '~/models/ApiResource'
- import type { Collection } from '~/types/data'
- import type Query from '~/services/data/Query'
- interface useEntityFetchReturnType {
- fetch: <T extends typeof ApiResource>(
- model: T,
- id?: number | null,
- ) => AsyncData<InstanceType<T> | null, Error | null>
- fetchCollection: <T extends typeof ApiResource>(
- model: T,
- parent?: T | null,
- query?: typeof Query | Query | null,
- ) => {
- data: ComputedRef<Collection<InstanceType<T>> | null>
- refresh: (
- opts?: AsyncDataExecuteOptions,
- ) => Promise<ComputedRef<Collection<InstanceType<T>>> | null>
- error: Ref<Error | null>
- status: Ref<AsyncDataRequestStatus>
- }
- getRef: <T extends ApiResource>(
- model: new () => T,
- id: Ref<number | null>,
- ) => ComputedRef<null | T>
- }
- export const useEntityFetch = (
- lazy: boolean = false,
- ): useEntityFetchReturnType => {
- const { em } = useEntityManager()
- const fetch = <T extends typeof ApiResource>(
- model: T,
- id?: number | null,
- ): AsyncData<InstanceType<T> | null, Error | null> => {
- return useAsyncData(
- model.entity + '_' + id + '_' + uuid4(),
- () => em.fetch(model, id),
- { lazy },
- )
- }
- const fetchCollection = <T extends typeof ApiResource>(
- model: T,
- parent: T | null = null,
- query: Query | null = null,
- ) => {
- const { data, refresh, error, status } = useAsyncData(
- model.entity + '_many_' + uuid4(),
- () => em.fetchCollection(model, parent, query),
- { lazy, deep: true },
- )
- return {
- data: computed(() => (data.value !== null ? data.value.value : null)),
- refresh,
- error,
- status,
- }
- }
- const getRef = <T extends ApiResource>(
- model: new () => T,
- id: Ref<number | null>,
- ): ComputedRef<T | null> => {
- return computed(() => (id.value ? (em.find(model, id.value) as T) : null))
- }
- return { fetch, fetchCollection, getRef }
- }
|