All files / apps/huella-legal/layers/newsletter/server/adapters kit.ts

100% Statements 12/12
100% Branches 6/6
100% Functions 2/2
100% Lines 11/11

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                        1x 8x 5x     3x   3x             1x 14x 14x     14x           7x   4x        
import type { H3Event } from "h3";
import type { FetchError } from "ofetch";
import type { SubscriptionError } from "../../shared/schemas/subscription";
 
/** https://developers.kit.com/api-reference/subscribers/create-a-subscriber */
interface KitSubscriber {
    subscriber: {
        id: number;
        state: "active" | "inactive" | "cancelled" | "bounced" | "complained";
    };
}
 
const handleRejection = (cause: FetchError): never => {
    if (cause.statusCode !== 422)
        throw createError({ statusCode: 502, statusMessage: "Kit is unavailable", cause });
 
    // eslint-disable-next-line no-console -- Kit's `errors` may name the address, so none is logged
    console.warn("[kit] refused an address");
 
    throw createError({
        statusCode: 422,
        statusMessage: "Invalid subscription",
        data: [{ name: "email", message: "rejected" }] satisfies SubscriptionError[],
    });
};
 
export const addSubscriber = async (event: H3Event, email: string): Promise<void> => {
    const { baseURL, apiKey, formId } = useRuntimeConfig(event).newsletter;
    const options = { baseURL, method: "POST", headers: { "X-Kit-Api-Key": apiKey } } as const;
 
    // Creating is an upsert that never changes an existing subscriber's state
    const { subscriber } = await $fetch<KitSubscriber>("/v4/subscribers", {
        ...options,
        body: { email_address: email, state: "inactive" },
    }).catch(handleRejection);
 
    // Kit doesn't document whether adding a cancelled subscriber to a form resubscribes them
    if (subscriber.state !== "inactive" && subscriber.state !== "active") return;
 
    await $fetch(`/v4/forms/${formId}/subscribers/${subscriber.id}`, options).catch(
        handleRejection,
    );
};