|
| 1 | +import { RequestContext } from "@decocms/start/sdk/requestContext"; |
| 2 | +import { usePlatform } from "../../apps/site"; |
| 3 | +import { readNewsletterCookie, serializeNewsletterCookie } from "../../loaders/_cookie"; |
| 4 | + |
| 5 | +export interface SubscribeNewsletterProps { |
| 6 | + email: string; |
| 7 | +} |
| 8 | + |
| 9 | +export interface SubscribeNewsletterResult { |
| 10 | + success: boolean; |
| 11 | + email: string; |
| 12 | +} |
| 13 | + |
| 14 | +async function action( |
| 15 | + props: SubscribeNewsletterProps, |
| 16 | + req?: Request, |
| 17 | +): Promise<SubscribeNewsletterResult> { |
| 18 | + const email = props?.email?.trim(); |
| 19 | + // The invoke endpoint is publicly POST-able, so validate here too (not just |
| 20 | + // via the form's type=email). Keep it minimal — a basic shape check. |
| 21 | + if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { |
| 22 | + throw new Error("a valid email is required"); |
| 23 | + } |
| 24 | + |
| 25 | + const request = req ?? RequestContext.current?.request; |
| 26 | + const platform = usePlatform(); |
| 27 | + |
| 28 | + if (platform === "vtex") { |
| 29 | + // TODO(consumer): real VTEX newsletter opt-in, e.g. |
| 30 | + // await invoke("vtex/actions/newsletter/subscribe.ts", { email }); |
| 31 | + } |
| 32 | + if (platform === "shopify") { |
| 33 | + // TODO(consumer): Shopify has no Storefront newsletter endpoint — integrate |
| 34 | + // a marketing provider (Klaviyo, Mailchimp, Resend) or set acceptsMarketing |
| 35 | + // on a customer mutation. |
| 36 | + } |
| 37 | + if (platform === "wake") { |
| 38 | + // TODO(consumer): wire wake newsletter endpoint here. |
| 39 | + } |
| 40 | + |
| 41 | + // Default: cookie-backed so the demo persists per-browser without a backend. |
| 42 | + // Idempotent — re-subscribing the same email is a no-op success. |
| 43 | + const emails = request ? readNewsletterCookie(request) : []; |
| 44 | + if (!emails.includes(email)) emails.push(email); |
| 45 | + |
| 46 | + RequestContext.responseHeaders.append("Set-Cookie", serializeNewsletterCookie(emails)); |
| 47 | + return { success: true, email }; |
| 48 | +} |
| 49 | + |
| 50 | +export default action; |
0 commit comments