All files / apps/huella-legal/layers/comments/server/adapters wordpress.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 5/5
100% Lines 14/14

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      1x           1x 10x   1x 5x   5x             1x 10x       1x       10x 10x 10x     10x                               5x      
import type { H3Event } from "h3";
import type { NewComment } from "../../shared/schemas/comment";
 
const REFUSALS: Record<string, { statusCode: number; statusMessage: string }> = {
    comment_duplicate: { statusCode: 409, statusMessage: "Duplicate comment" },
    comment_flood: { statusCode: 429, statusMessage: "Commenting too fast" },
    rest_comment_closed: { statusCode: 410, statusMessage: "Comments are closed" },
};
 
const escapeHtml = (text: string): string =>
    text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
 
const toRefusal = (cause: unknown) => {
    const code = (cause as { data?: { code?: string } }).data?.code;
 
    return createError({
        ...(REFUSALS[code ?? ""] ?? { statusCode: 502, statusMessage: "WordPress is unavailable" }),
        cause,
    });
};
 
// The only client-address header Netlify guarantees; `X-Forwarded-For` covers `nuxi preview`
const readerIP = (event: H3Event): string | undefined =>
    getRequestHeader(event, "x-nf-client-connection-ip") ??
    getRequestIP(event, { xForwardedFor: true });
 
/** Files a reader's comment into WordPress's moderation queue, as the reader rather than as us. */
export const createComment = async (
    event: H3Event,
    { post, parent, name, email, content }: Omit<NewComment, "consent">,
): Promise<void> => {
    const { content: cms, comments } = useRuntimeConfig(event);
    const { username, applicationPassword } = comments;
    const credentials = btoa(`${username}:${applicationPassword}`);
 
    // https://developer.wordpress.org/rest-api/reference/comments/#create-a-comment
    await $fetch("/wp-json/wp/v2/comments", {
        baseURL: cms.vendor.baseURL,
        method: "POST",
        headers: { Authorization: `Basic ${credentials}` },
        body: {
            post: Number(post),
            parent: Number(parent),
            author_name: name.replace(/[<>]/g, ""),
            author_email: email,
            content: escapeHtml(content),
            // Akismet
            author_ip: readerIP(event),
            author_user_agent: getRequestHeader(event, "user-agent"),
            status: "hold",
        },
    }).catch((cause: unknown) => {
        throw toRefusal(cause);
    });
};