All files / packages/content/src/testing wordpress.ts

100% Statements 44/44
91.83% Branches 45/49
100% Functions 15/15
100% Lines 35/35

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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137                              2x 31x   46x   31x 59x         2x 30x   30x   12x 36x     22x     2x 105x           2x   92x   65x                   37x                   40x                                                   2x       15x 13x   2x       2x   15x   15x   14x 14x 14x 15x   15x 41x     15x     15x 1x     13x                
import { escapeText } from "entities";
import { http, HttpResponse, type HttpHandler } from "msw";
import { API_PATH, TAXONOMIES } from "#core/adapters/providers/wordpress/WordpressConfigs";
import type {
    WordpressEntry,
    WordpressTerm,
    WordpressUser,
    WordpressYoast,
} from "#core/adapters/providers/wordpress/WordpressTypes";
import type { Author, Entry, EntryResource, SEO, Term, TermResource } from "#core/domain/content";
 
export type WordpressContent = Partial<
    Record<EntryResource, Entry[]> & Record<TermResource, Term[]>
>;
 
const inTerms = (item: WordpressEntry | WordpressTerm, query: URLSearchParams): boolean => {
    if (!("_embedded" in item)) return true;
 
    const termIds = new Set(item._embedded?.["wp:term"]?.flat().map(({ id }) => String(id)));
 
    return Object.values(TAXONOMIES).every(
        (resource) => !resource || !query.has(resource) || termIds.has(query.get(resource) ?? ""),
    );
};
 
// WordPress matches every word of the search, case-insensitively, against the title, excerpt or body
const inSearch = (item: WordpressEntry | WordpressTerm, query: URLSearchParams): boolean => {
    const words = query.get("search")?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
 
    if (!words.length || !("_embedded" in item)) return true;
 
    const text = [item.title, item.excerpt, item.content]
        .map((field) => field?.rendered.toLowerCase() ?? "")
        .join(" ");
 
    return words.every((word) => text.includes(word));
};
 
const toYoast = (seo?: SEO): WordpressYoast | undefined =>
    seo && {
        title: seo.title,
        description: seo.description,
        robots: { index: seo.noindex ? "noindex" : "index" },
    };
 
const toWordpressTerm = (term: Term): WordpressTerm => {
    const taxonomy =
        Object.keys(TAXONOMIES).find((name) => TAXONOMIES[name] === term.resource) ?? term.resource;
 
    return {
        id: Number(term.id),
        name: escapeText(term.name),
        slug: term.slug,
        taxonomy,
        description: term.description && escapeText(term.description),
        yoast_head_json: toYoast(term.seo),
    };
};
 
const toWordpressUser = (author: Author): WordpressUser => ({
    id: Number(author.id),
    name: escapeText(author.name),
    slug: author.slug,
    description: author.bio && escapeText(author.bio),
    simple_local_avatar: author.avatar
        ? { media_id: Number(author.avatar.id), full: author.avatar.url }
        : false,
});
 
const toWordpressEntry = (entry: Entry): WordpressEntry => ({
    id: Number(entry.id),
    slug: entry.slug,
    title: { rendered: escapeText(entry.title) },
    content: { rendered: entry.body.value },
    excerpt: entry.excerpt && { rendered: entry.excerpt.value },
    date_gmt: entry.publishedAt?.replace(/Z$/, ""),
    modified_gmt: entry.updatedAt?.replace(/Z$/, ""),
    yoast_head_json: toYoast(entry.seo),
    acf: entry.fields ?? [],
    _embedded: {
        "wp:featuredmedia": entry.image
            ? [
                  {
                      id: Number(entry.image.id),
                      source_url: entry.image.url,
                      alt_text: entry.image.alt,
                      media_details: { width: entry.image.width, height: entry.image.height },
                  },
              ]
            : [],
        "wp:term": [entry.terms.map(toWordpressTerm)],
        author: entry.authors.map(toWordpressUser),
    },
});
 
const toWordpress = (
    resource: keyof WordpressContent,
    content: WordpressContent,
): (WordpressEntry | WordpressTerm)[] | undefined => {
    if (resource === "posts" || resource === "pages")
        return content[resource]?.map(toWordpressEntry);
 
    return content[resource]?.map(toWordpressTerm);
};
 
/** MSW handlers that serve domain entries and terms the way WordPress's REST API would. */
export const wordpressHandlers = (baseURL: string, content: WordpressContent): HttpHandler[] => [
    http.get(`${baseURL}${API_PATH}/:resource`, ({ params, request }) => {
        const items = toWordpress(params.resource as keyof WordpressContent, content);
 
        if (!items) return HttpResponse.json({ code: "rest_no_route" }, { status: 404 });
 
        const query = new URL(request.url).searchParams;
        const slug = query.get("slug");
        const page = Number(query.get("page") ?? 1);
        const perPage = Number(query.get("per_page") ?? 10);
 
        const matches = items.filter(
            (item) =>
                (!slug || item.slug === slug) && inTerms(item, query) && inSearch(item, query),
        );
        const totalPages = Math.max(1, Math.ceil(matches.length / perPage));
 
        // WordPress refuses a page past the end rather than answering an empty one
        if (page > totalPages) {
            return HttpResponse.json({ code: "rest_post_invalid_page_number" }, { status: 400 });
        }
 
        return HttpResponse.json(matches.slice((page - 1) * perPage, page * perPage), {
            headers: {
                "x-wp-total": String(matches.length),
                "x-wp-totalpages": String(totalPages),
            },
        });
    }),
];