All files / apps/huella-legal/layers/archive/app/composables useArticleListing.ts

100% Statements 26/26
84.61% Branches 11/13
100% Functions 11/11
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65          4x     11x 11x 11x   11x 1x               11x   11x 2x 1x     11x 2x 2x     11x   11x 2x     11x 2x   2x   1x             2x                 11x   10x    
import type { RouteLocationRaw } from "vue-router";
import type { FilterPill } from "~/components/listing/FilterPills.vue";
 
type Sort = ListingQuery["sort"];
 
export const useArticleListing = async (
    scope: Pick<ListingQuery, "category" | "tag" | "author"> = {},
) => {
    const { t } = useI18n();
    const route = useRoute();
    const { link, navigate } = useListingQuery({ page: "1", sort: "newest" });
 
    const request = useCachedFetch<ArticleListing>("/api/articles", {
        query: computed(() => ({
            ...scope,
            page: route.query.page,
            sort: route.query.sort,
            format: route.query.format,
            query: route.query.query,
        })),
    });
    const { data: listing, status } = request;
 
    const sort = computed<Sort>({
        get: () => (route.query.sort === "oldest" ? "oldest" : "newest"),
        set: (value) => void navigate({ sort: value }),
    });
 
    const search = computed<string>({
        get: () => (typeof route.query.query === "string" ? route.query.query : ""),
        set: (value) => void navigate({ query: value.trim() || undefined }),
    });
 
    const pageLink = (page: number): RouteLocationRaw => link({ page: String(page) });
 
    const archiveTotal = computed<number>(
        () => listing.value?.formats.reduce((sum, { count }) => sum + count, 0) ?? 0,
    );
 
    const formatPills = computed<FilterPill[]>(() => {
        const formats = listing.value?.formats ?? [];
 
        if (formats.length < 2) return [];
 
        return [
            {
                label: t("articleListing.formats.all"),
                count: archiveTotal.value,
                to: link({ format: undefined }),
                active: !route.query.format,
            },
            ...formats.map(({ value, count }) => ({
                label: t(`articleListing.formats.${FORMAT_KEYS[value]}`),
                count,
                to: link({ format: value }),
                active: route.query.format === value,
            })),
        ];
    });
 
    await useFailOnError(request, { refetches: true });
 
    return { listing, status, sort, search, archiveTotal, formatPills, pageLink };
};