All files / apps/huella-legal/layers/newsletter/server/api newsletter.post.ts

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

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        3x     7x   7x   6x   5x   5x     1x                                                        
import type { NewsletterRequest } from "../../shared/types/NewsletterRequest";
import { subscriptionSchema } from "../../shared/schemas/subscription";
import { addSubscriber } from "../adapters/kit";
 
const schema = subscriptionSchema((issue) => issue);
 
export default defineEventHandler(async (event): Promise<void> => {
    const body = (await readBody<Partial<NewsletterRequest> | null>(event)) ?? {};
 
    if (body.honeypot) return;
 
    await assertChallenge(event, body.token);
 
    const { email } = assertForm(schema, body);
 
    await addSubscriber(event, email);
});
 
defineRouteMeta({
    openAPI: {
        tags: ["Forms"],
        summary: "Subscribe an email to the newsletter",
        requestBody: {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        type: "object",
                        required: ["email", "token"],
                        properties: {
                            email: { type: "string", format: "email" },
                            token: { type: "string", description: "A Turnstile token" },
                            honeypot: { type: "string", description: "Left empty" },
                        },
                    },
                },
            },
        },
        responses: {
            204: { description: "Subscribed, or silently dropped when the honeypot is filled" },
            403: { description: "The Turnstile challenge failed" },
            422: { description: "One `{ name, message }` per invalid field, under `data`" },
            502: { description: "Kit or Turnstile is unavailable" },
        },
    },
});