AbiirSkincare/Hydrogen/web/app/lib/newsletter.ts

94 lines
2.8 KiB
TypeScript

import type {QueryResponseInitial} from '@sanity/react-loader';
import type {SanityContext} from 'hydrogen-sanity';
export type NewsletterSectionCms = {
eyebrow: string;
headlinePlain: string;
headlineItalic: string;
body: string;
emailPlaceholder: string;
submitButtonLabel: string;
successTitle: string;
successSubtitle: string;
perks: string[];
};
type SanityNewsletterPayload = {
eyebrow?: string | null;
headlinePlain?: string | null;
headlineItalic?: string | null;
body?: string | null;
emailPlaceholder?: string | null;
submitButtonLabel?: string | null;
successTitle?: string | null;
successSubtitle?: string | null;
perks?: Array<string | null> | null;
} | null;
/** Mirrors `React/src/app/components/Newsletter.tsx` defaults for local preview. */
export const MOCK_NEWSLETTER_SECTION_CMS: NewsletterSectionCms = {
eyebrow: 'Join the GLOW CLUB',
headlinePlain: 'Skincare Secrets,',
headlineItalic: 'Delivered',
body: 'Subscribe for exclusive early access to new launches, curated skincare rituals, expert tips, and a welcome gift of 15% off your first order.',
emailPlaceholder: 'Your email address',
submitButtonLabel: 'Subscribe',
successTitle: 'Welcome to the ABiiR family',
successSubtitle: 'Check your inbox for your 15% welcome code',
perks: [
'15% Off First Order',
'Early Access',
'Expert Skincare Tips',
'Free Shipping Offers',
],
};
export function normalizeNewsletterSanityPayload(
raw: unknown,
): NewsletterSectionCms | null {
if (raw == null || typeof raw !== 'object') return null;
const b = raw as SanityNewsletterPayload;
if (
!b?.eyebrow ||
!b?.headlinePlain ||
!b?.headlineItalic ||
!b?.body
) {
return null;
}
const perks = (b.perks ?? [])
.map((p) => (typeof p === 'string' ? p.trim() : ''))
.filter(Boolean);
if (!perks.length) return null;
return {
eyebrow: b.eyebrow,
headlinePlain: b.headlinePlain,
headlineItalic: b.headlineItalic,
body: b.body,
emailPlaceholder: b.emailPlaceholder ?? 'Your email address',
submitButtonLabel: b.submitButtonLabel ?? 'Subscribe',
successTitle: b.successTitle ?? 'Welcome to the ABiiR family',
successSubtitle:
b.successSubtitle ?? 'Check your inbox for your 15% welcome code',
perks,
};
}
export async function loadNewsletterFromSanity(args: {
sanity: SanityContext;
groq: string;
}): Promise<{newsletterCms: NewsletterSectionCms}> {
const initial: QueryResponseInitial<SanityNewsletterPayload> =
await args.sanity.loadQuery<SanityNewsletterPayload>(args.groq).catch(
(): QueryResponseInitial<SanityNewsletterPayload> => ({
data: null,
sourceMap: undefined,
}),
);
const normalized = normalizeNewsletterSanityPayload(initial.data);
return {
newsletterCms: normalized ?? MOCK_NEWSLETTER_SECTION_CMS,
};
}