All files / apps/portfolio/app/composables useSiteData.ts

100% Statements 34/34
100% Branches 6/6
100% Functions 20/20
100% Lines 24/24

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    7x                       7x 94x 94x   87x 175x     94x 1x     93x     7x   16x   16x 48x       45x   7x 4x 12x     7x 16x   27x     7x 27x         48x   54x  
import type { SiteData } from "~/types/SiteData";
 
const EMPTY: SiteData = {
    benchmarks: [],
    decisions: [],
    workflows: { projects: [], templates: [], lessons: 0 },
    rules: null,
    specs: null,
};
 
/**
 * One cut of the portal's payload under its own key, so a page's payload carries only that cut.
 * With `dataUrl` unset every cut is empty; set, a failed fetch fails the page and so the build.
 */
const useSiteData = async <T>(key: string, pick: (data: SiteData) => T) => {
    const { dataUrl } = useRuntimeConfig().public;
    const result = await useAsyncData(
        `site-${key}`,
        async () => pick(dataUrl ? await $fetch<SiteData>(dataUrl) : EMPTY),
        { default: () => pick(EMPTY) },
    );
 
    if (result.error.value) {
        throw createError({ status: 502, message: `${dataUrl}: ${result.error.value.message}` });
    }
 
    return result;
};
 
export const useBenchmarks = () => {
    // Read before the fetch: `useAppConfig()` inside the handler runs after an await, without Nuxt
    const portal = useAppConfig().portalUrl;
 
    return useSiteData("benchmarks", ({ benchmarks }) =>
        benchmarks.map((item) => ({ ...item, screenshot: `${portal}${item.screenshot}` })),
    );
};
 
export const useDecisionReports = () => useSiteData("decisions", ({ decisions }) => decisions);
 
export const useWorkflowMaps = () =>
    useSiteData("workflow-maps", ({ workflows }) =>
        workflows.projects.map(({ id, title, map }) => ({ id, title, map })),
    );
 
export const useWorkflowGlyph = (id: string) =>
    useSiteData(
        `workflow-glyph-${id}`,
        ({ workflows }) => workflows.projects.find((project) => project.id === id)?.glyph ?? null,
    );
 
export const useWorkflowTemplates = () =>
    useSiteData("workflow-templates", ({ workflows }) => ({
        templates: workflows.templates,
        lessons: workflows.lessons,
    }));
 
export const useRuleCounts = () => useSiteData("rule-counts", ({ rules }) => rules);
 
export const useSpecTotal = () => useSiteData("spec-total", ({ specs }) => specs);