Skip to content
Snippets Groups Projects
useFetchMsDocument.ts 2.10 KiB
import { MeiliSearch } from 'meilisearch'
import { useRuntimeConfig, watchEffect, type MaybeRef, ref, toValue } from '#imports'
import type { FacetDistribution, Hits } from 'meilisearch';
import { useAsyncState } from '@vueuse/core'
import { errorMonitor } from 'events';

export async function useFetchMsDocument(
    index: MaybeRef<string> = ref(""),
    search: Ref<string> = ref(""),
    filter: Ref<string> = ref(''),
    limit: Ref<number> = ref(1000),
    hitsPerPage: Ref<number> = ref(25),
    page: Ref<number> = ref(1),
    facets: Ref<string[]> = ref([]),
    sort: Ref<string[]> = ref([]),
) {
    const runtimeConfig = useRuntimeConfig();

    const client = new MeiliSearch({
        host: runtimeConfig.public.meilisearchClient.hostUrl,
        apiKey: runtimeConfig.public.meilisearchClient.searchApiKey
    })
    const pending = ref(false)
    const filterError: Ref<string | null> = ref(null)
    const hits: Ref<Hits<Record<string, any>>> = ref([])
    const totalHits = ref(0)
    const totalPages = ref(0)
    const facetDistribution: Ref<FacetDistribution | undefined> = ref({})
    watch(filter, () => {
        page.value = 1

    })
    watch(search, () => {
        page.value = 1

    })

    try {
        pending.value = true
        const res = await client
            .index(toValue(index))
            .search(toValue(search), {
                limit: toValue(limit),
                filter: toValue(filter),
                hitsPerPage: toValue(hitsPerPage),
                page: toValue(page),
                facets: toValue(facets),
                sort: toValue(sort),
            })
        filterError.value = null
        const { hits: resHits, totalHits: resTotalHits, totalPages: resTotalPages, facetDistribution: facetD } = res

        totalHits.value = resTotalHits
        hits.value = resHits
        totalPages.value = resTotalPages
        facetDistribution.value = facetD
        pending.value = false
    } catch (e: any) {
        filterError.value = e
    }
    finally {
        pending.value = false
    }
    return { hits, totalHits, pending, filterError, totalPages, facetDistribution }
}