All files / apps/huella-legal/layers/articles/server/services articleIndex.ts

100% Statements 18/18
66.66% Branches 4/6
100% Functions 5/5
100% Lines 15/15

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                1x   1x 1x   7x         1x   4x   4x   3x 3x 7x   3x     3x   3x           1x       4x    
import { MAX_PER_PAGE } from "@joinery/content";
import type { H3Event } from "h3";
import type { ArticleSummary } from "../../shared/types/ArticleSummary";
import { readSaved, save } from "../adapters/netlify";
import { toArticleSummary } from "../mappers/articleSummary";
import { isListed } from "./hiddenTerms";
import { readAllPages } from "../utils/readAllPages";
 
const { cache } = useRuntimeConfig().articles;
 
const STORE = "article-index";
const KEY = "posts";
 
const newestFirst = (a: ArticleSummary, b: ArticleSummary): number =>
    (b.publishedAt ?? "").localeCompare(a.publishedAt ?? "");
 
// Nitro's cache lives in one function instance's memory, so a cold instance reads the deploy's
// saved copy before it pages through every post in WordPress
const readArticleIndex = defineCachedFunction(
    async (event: H3Event): Promise<ArticleSummary[]> => {
        const saved = await readSaved<ArticleSummary[]>(STORE, KEY, cache.maxAge);
 
        if (saved) return saved;
 
        const content = useContent(event);
        const entries = await readAllPages((page) =>
            content.listEntries("posts", { page, perPage: MAX_PER_PAGE }),
        );
        const index = entries.map(toArticleSummary).sort(newestFirst);
 
        // Awaited, since Netlify may freeze the function once the response is sent
        await save(STORE, KEY, index);
 
        return index;
    },
    {
        name: "article-index",
        group: "articles",
        ...cache,
        getKey: () => KEY,
    },
);
 
export const getArticleIndex = async (event: H3Event): Promise<ArticleSummary[]> =>
    (await readArticleIndex(event)).filter(isListed);