All files / apps/wp-editor/server/adapters wordpress.ts

81.81% Statements 18/22
80% Branches 8/10
63.63% Functions 7/11
80.95% Lines 17/21

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                                                                2x 66x   66x                         2x       2x         1x 1x       1x   1x     3x 6x       3x 3x 3x 3x     6x           1x                              
import { ofetch } from "ofetch";
import type { BaseMeta } from "../../shared/types/BaseMeta.ts";
import type { PostType } from "../../shared/types/PostType.ts";
import type { Proposal } from "../../shared/types/Proposal.ts";
import type { Snapshot } from "../../shared/types/Snapshot.ts";
 
export interface WordPressCredentials {
    baseURL: string;
    username: string;
    applicationPassword: string;
}
 
/** The `?context=edit` shape, trimmed to what the editor reads. */
export interface WpPost {
    id: number;
    type: string;
    status: string;
    date: string;
    modified_gmt: string;
    link: string;
    title: { raw: string };
    excerpt: { raw: string };
    content: { raw: string };
    _embedded?: {
        author?: { name?: string }[];
        "wp:featuredmedia"?: {
            source_url?: string;
            media_details?: { sizes?: { thumbnail?: { source_url?: string } } };
        }[];
    };
}
 
export const toSnapshot = (post: WpPost): Snapshot & BaseMeta => {
    const media = post._embedded?.["wp:featuredmedia"]?.[0];
 
    return {
        title: post.title.raw,
        excerpt: post.excerpt.raw,
        content: post.content.raw,
        modifiedGmt: post.modified_gmt,
        date: post.date,
        status: post.status,
        link: post.link,
        author: post._embedded?.author?.[0]?.name ?? "",
        image: media?.media_details?.sizes?.thumbnail?.source_url ?? media?.source_url ?? null,
    };
};
 
const PAGE_SIZE = 100;
 
export type WordPress = ReturnType<typeof createWordPress>;
 
export const createWordPress = ({
    baseURL,
    username,
    applicationPassword,
}: WordPressCredentials) => {
    const credentials = btoa(`${username}:${applicationPassword}`);
    const api = ofetch.create({
        baseURL: `${baseURL}/wp-json/wp/v2`,
        headers: { Authorization: `Basic ${credentials}` },
    });
    const edit = { context: "edit", _embed: "author,wp:featuredmedia" };
 
    return {
        /** Every item of `type` in `status`, following WordPress's `X-WP-TotalPages`. */
        list: async (type: PostType, status = "publish"): Promise<WpPost[]> => {
            const fetchPage = (page: number) =>
                api.raw<WpPost[]>(`/${type}`, {
                    query: { ...edit, status, per_page: PAGE_SIZE, page },
                });
 
            const first = await fetchPage(1);
            const pages = Number(first.headers.get("x-wp-totalpages") ?? 1);
            const rest = await Promise.all(
                Array.from({ length: Math.max(pages - 1, 0) }, (_, index) => fetchPage(index + 2)),
            );
 
            return [first, ...rest].flatMap((response) => response._data ?? []);
        },
 
        get: (type: PostType, id: number) => api<WpPost>(`/${type}/${id}`, { query: edit }),
 
        update: (type: PostType, id: number, { content, title, excerpt }: Proposal) =>
            api<WpPost>(`/${type}/${id}`, {
                method: "PUT",
                query: { context: "edit" },
                body: { content, title, excerpt },
            }),
 
        create: (type: PostType, body: Record<string, string>) =>
            api<WpPost>(`/${type}`, { method: "POST", query: { context: "edit" }, body }),
 
        remove: (type: PostType, id: number) =>
            api(`/${type}/${id}`, { method: "DELETE", query: { force: true } }),
 
        revisions: (type: PostType, id: number) => api<unknown[]>(`/${type}/${id}/revisions`),
    };
};