All files / apps/huella-legal/layers/articles/server/api search.get.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 3/3
100% Lines 17/17

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 66 67 68 69 70 71 72 73 74 75                  1x   1x         1x 7x   1x 12x   12x   6x       12x   12x           5x 5x 5x               5x   4x   1x     1x                                          
import { MAX_SEARCH_LENGTH } from "@joinery/content";
import type { H3Event } from "h3";
import * as v from "valibot";
import type { ArticleSearch } from "../../shared/types/ArticleSearch";
import { toArticleSearch, toSuggestedSubjects } from "../mappers/articleSearch";
import { getArticleIndex } from "../services/articleIndex";
import { withCommentCounts } from "../services/commentCounts";
import { isListed } from "../services/hiddenTerms";
 
const PER_PAGE = 20;
 
const searchQuerySchema = v.object({
    query: v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(MAX_SEARCH_LENGTH)),
    page: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)), "1"),
});
 
const notFound = (message: string) =>
    createError({ statusCode: 404, statusMessage: "Search not found", message });
 
const parseSearchQuery = (event: H3Event) => {
    const result = v.safeParse(searchQuerySchema, getQuery(event));
 
    if (!result.success) throw notFound(v.summarize(result.issues));
 
    return result.output;
};
 
export default defineEventHandler(async (event): Promise<ArticleSearch> => {
    const { query, page } = parseSearchQuery(event);
 
    const results = await useContent(event).listEntries("posts", {
        search: query,
        page,
        perPage: PER_PAGE,
    });
 
    const found = toArticleSearch(query, results);
    const listed = found.items.filter(isListed);
    const search = {
        ...found,
        items: await withCommentCounts(event, listed),
        // Only this page's hidden matches are known, so a later page can still overcount
        total: found.total - (found.items.length - listed.length),
    };
 
    // WP only refuses a page past the end when something matched
    if (page > search.totalPages) throw notFound(`"page" is past the end for "${query}"`);
 
    if (search.total) return search;
 
    return { ...search, subjects: toSuggestedSubjects(await getArticleIndex(event)) };
});
 
defineRouteMeta({
    openAPI: {
        tags: ["Articles"],
        summary: "Search articles, suggesting subjects when nothing matches",
        parameters: [
            {
                name: "query",
                in: "query",
                required: true,
                // `MAX_SEARCH_LENGTH` from `@joinery/content`, since route meta only takes literals
                description: "1 to 100 characters, trimmed",
                schema: { type: "string" },
            },
            { name: "page", in: "query", schema: { type: "integer", minimum: 1, default: 1 } },
        ],
        responses: {
            200: { description: "Twenty results per page" },
            404: { description: "The query is invalid or the page is past the end" },
        },
    },
});