All files / apps/huella-legal/layers/forms/server/utils resend.ts

100% Statements 4/4
100% Branches 2/2
100% Functions 2/2
100% Lines 4/4

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                                  1x       9x     9x                         4x      
import type { H3Event } from "h3";
 
interface Attachment {
    filename: string;
    /** Base64. */
    content: string;
}
 
interface Mail {
    to: string;
    replyTo: string;
    subject: string;
    text: string;
    attachments?: Attachment[];
}
 
/** Sends a plain-text email from the site's sender, answering as `replyTo`; `502` if Resend fails. */
export const sendMail = async (
    event: H3Event,
    { to, replyTo, subject, text, attachments }: Mail,
): Promise<void> => {
    const { baseURL, apiKey, from } = useRuntimeConfig(event).mail;
 
    // https://resend.com/docs/api-reference/emails/send-email
    await $fetch("/emails", {
        baseURL,
        method: "POST",
        headers: { Authorization: `Bearer ${apiKey}` },
        body: {
            from,
            to,
            reply_to: replyTo,
            subject: subject.replace(/\s+/g, " "),
            text,
            ...(attachments?.length && { attachments }),
        },
    }).catch((cause: unknown) => {
        throw createError({ statusCode: 502, statusMessage: "Resend is unavailable", cause });
    });
};