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

100% Statements 13/13
100% Branches 4/4
100% Functions 5/5
100% Lines 11/11

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        1x   1x   2x   3x   1x           1x         1x       2x   2x 3x   3x      
import type { H3Event } from "h3";
import type { ArticleSummary } from "../../shared/types/ArticleSummary";
import { listCommentedPosts } from "../adapters/wordpress";
 
const { cache } = useRuntimeConfig().articles;
 
const getCommentCounts = defineCachedFunction(
    async (event: H3Event): Promise<Record<string, number>> => {
        const counts: Record<string, number> = {};
 
        for (const post of await listCommentedPosts(event)) counts[post] = (counts[post] ?? 0) + 1;
 
        return counts;
    },
    {
        name: "comment-counts",
        group: "articles",
        ...cache,
        getKey: () => "comments",
    },
);
 
/** Puts each post's comment count on its summary; a failed count leaves the cards without one. */
export const withCommentCounts = async (
    event: H3Event,
    summaries: ArticleSummary[],
): Promise<ArticleSummary[]> => {
    const counts = await getCommentCounts(event).catch((): Record<string, number> => ({}));
 
    return summaries.map((summary) => {
        const commentCount = counts[summary.id];
 
        return commentCount ? { ...summary, commentCount } : summary;
    });
};