Updates the packages and the banner live in the browser
The build still bakes the current packages and the active banner into the HTML. After hydration the page asks /api/v1/offerings and /api/v1/offerings/banner once and replaces what differs; errors and time-outs keep what was baked, and a 204 from the banner route hides the banner. The banner is now the OfferingBanner contract (title, text, optional link) instead of layout=banner. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,11 @@
|
||||
// https://test.andreaslop.nl (the API is same-origin, /api/v1/offerings).
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { mapOfferings, type SiteOfferings } from './offerings.ts';
|
||||
import {
|
||||
mapBanner,
|
||||
mapOfferings,
|
||||
type SiteOfferings,
|
||||
} from '../src/lib/offerings.ts';
|
||||
|
||||
const SNAPSHOT = fileURLToPath(
|
||||
new URL('../src/content/offerings.snapshot.json', import.meta.url),
|
||||
@@ -19,14 +23,17 @@ const GENERATED = fileURLToPath(
|
||||
const TIMEOUT_MS = 10_000;
|
||||
const ATTEMPTS = 2;
|
||||
|
||||
async function fetchAnswer(base: string): Promise<unknown> {
|
||||
const url = new URL('/api/v1/offerings', base);
|
||||
// The JSON answer, or undefined for 204 (no content). Other statuses and
|
||||
// network errors throw.
|
||||
async function fetchAnswer(base: string, path: string): Promise<unknown> {
|
||||
const url = new URL(path, base);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (response.status === 204) return undefined;
|
||||
if (!response.ok) throw new Error(`status ${response.status}`);
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
@@ -45,13 +52,35 @@ async function main() {
|
||||
console.log('[offerings] no OFFERINGS_URL: using the snapshot');
|
||||
} else {
|
||||
try {
|
||||
const mapped = mapOfferings(await fetchAnswer(base));
|
||||
const mapped = mapOfferings(
|
||||
await fetchAnswer(base, '/api/v1/offerings'),
|
||||
);
|
||||
if (mapped) {
|
||||
result = { ...mapped, source: 'cms' };
|
||||
result = {
|
||||
...snapshot,
|
||||
packages: mapped.packages,
|
||||
source: 'cms',
|
||||
};
|
||||
console.log(
|
||||
`[offerings] ${mapped.packages.length} packages` +
|
||||
`${mapped.banner ? ' and a banner' : ''} from ${base}`,
|
||||
`[offerings] ${mapped.packages.length} packages from ${base}`,
|
||||
);
|
||||
// The banner: 200 is the active one, 204 means none. A
|
||||
// failing banner call keeps the snapshot's banner (none).
|
||||
try {
|
||||
const banner = mapBanner(
|
||||
await fetchAnswer(base, '/api/v1/offerings/banner'),
|
||||
);
|
||||
result.banner = banner;
|
||||
console.log(
|
||||
banner
|
||||
? `[offerings] banner "${banner.title}"`
|
||||
: '[offerings] no active banner',
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[offerings] banner not available (${String(error)}): none`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.warn(
|
||||
`[offerings] answer of ${base} has no valid package: using the snapshot`,
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mapOfferings, parsePriceText } from './offerings';
|
||||
|
||||
const card = (over: Record<string, unknown> = {}) => ({
|
||||
id: 'x',
|
||||
slug: 'newborn',
|
||||
title: 'Newborn',
|
||||
description: 'Mooie shoot',
|
||||
price: '€ 185',
|
||||
priceNote: 'incl. galerij',
|
||||
features: ['1-2 uur fotografie', 'Online galerij'],
|
||||
ctaLabel: 'Boek',
|
||||
featured: false,
|
||||
displayOrder: 2,
|
||||
categoryId: null,
|
||||
category: null,
|
||||
layout: 'card',
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('parsePriceText', () => {
|
||||
it.each([
|
||||
['€ 175', 175],
|
||||
['€ 1.250', 1250],
|
||||
['175,-', 175],
|
||||
['€ 175,00', 175],
|
||||
['€\u00a0185', 185],
|
||||
])('leest %s als %i', (text, euros) => {
|
||||
expect(parsePriceText(text)).toBe(euros);
|
||||
});
|
||||
|
||||
it.each(['', 'op aanvraag', '€ 12,50', '€ 0', '175 of 185', null, 12])(
|
||||
'geeft geen prijs voor %j',
|
||||
(text) => {
|
||||
expect(parsePriceText(text)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('geeft terug wat formatteren als hele euros oplevert', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.integer({ min: 1, max: 99_999 }), (euros) => {
|
||||
const grouped = euros.toLocaleString('nl-NL');
|
||||
expect(parsePriceText(`€ ${grouped}`)).toBe(euros);
|
||||
expect(parsePriceText(`€ ${euros}`)).toBe(euros);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapOfferings', () => {
|
||||
it('maakt pakketten in volgorde van displayOrder', () => {
|
||||
const result = mapOfferings([
|
||||
card({ slug: 'gezin', title: 'Gezin', displayOrder: 3 }),
|
||||
card({
|
||||
slug: 'zwangerschap',
|
||||
title: 'Zwangerschap',
|
||||
displayOrder: 1,
|
||||
}),
|
||||
card(),
|
||||
]);
|
||||
expect(result?.packages.map((p) => p.id)).toEqual([
|
||||
'zwangerschap',
|
||||
'newborn',
|
||||
'gezin',
|
||||
]);
|
||||
expect(result?.packages[1]).toMatchObject({
|
||||
name: 'Newborn',
|
||||
price: 185,
|
||||
priceNote: 'incl. galerij',
|
||||
ctaLabel: 'Boek',
|
||||
});
|
||||
expect(result?.banner).toBeNull();
|
||||
});
|
||||
|
||||
it('houdt de banner buiten de pakketten en neemt de eerste bruikbare', () => {
|
||||
const result = mapOfferings([
|
||||
card(),
|
||||
card({
|
||||
slug: 'actie',
|
||||
title: 'Kerstactie',
|
||||
price: '€ 99 i.p.v. € 150',
|
||||
layout: 'banner',
|
||||
displayOrder: 9,
|
||||
}),
|
||||
card({
|
||||
slug: 'actie2',
|
||||
title: 'Tweede',
|
||||
layout: 'banner',
|
||||
displayOrder: 10,
|
||||
}),
|
||||
]);
|
||||
expect(result?.packages.map((p) => p.id)).toEqual(['newborn']);
|
||||
expect(result?.banner).toMatchObject({
|
||||
title: 'Kerstactie',
|
||||
priceText: '€ 99 i.p.v. € 150',
|
||||
});
|
||||
});
|
||||
|
||||
it('neemt een banner met alleen een titel; lege velden blijven leeg', () => {
|
||||
const result = mapOfferings([
|
||||
card(),
|
||||
card({
|
||||
slug: 'actie',
|
||||
title: 'Past er niets bij?',
|
||||
description: '',
|
||||
price: '',
|
||||
priceNote: '',
|
||||
ctaLabel: '',
|
||||
features: [],
|
||||
layout: 'banner',
|
||||
}),
|
||||
]);
|
||||
expect(result?.banner).toEqual({
|
||||
title: 'Past er niets bij?',
|
||||
description: undefined,
|
||||
priceText: undefined,
|
||||
priceNote: undefined,
|
||||
features: [],
|
||||
ctaLabel: undefined,
|
||||
});
|
||||
expect(
|
||||
mapOfferings([card(), card({ title: ' ', layout: 'banner' })])
|
||||
?.banner,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('slaat ongeldige kaarten over en behoudt de rest', () => {
|
||||
const result = mapOfferings([
|
||||
card({ slug: 'Slecht Id' }),
|
||||
card({ slug: 'a', price: 'op aanvraag' }),
|
||||
card({ slug: 'b', title: ' ' }),
|
||||
card({ slug: 'c', features: [] }),
|
||||
card({ slug: 'd', features: ['ok', ''] }),
|
||||
card({ slug: 'newborn' }),
|
||||
card({ slug: 'newborn', title: 'Dubbel' }),
|
||||
]);
|
||||
expect(result?.packages.map((p) => p.id)).toEqual(['newborn']);
|
||||
expect(result?.packages[0].name).toBe('Newborn');
|
||||
});
|
||||
|
||||
it('verwerpt een antwoord zonder geldig pakket', () => {
|
||||
expect(mapOfferings([])).toBeNull();
|
||||
expect(mapOfferings([card({ price: '' })])).toBeNull();
|
||||
expect(mapOfferings([card({ layout: 'banner' })])).toBeNull();
|
||||
expect(mapOfferings({ items: [] })).toBeNull();
|
||||
expect(mapOfferings(null)).toBeNull();
|
||||
expect(mapOfferings('fout')).toBeNull();
|
||||
});
|
||||
|
||||
it('geeft nooit een pakket met lege of ongeldige prijs terug, wat er ook komt', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(fc.jsonValue()), (answer) => {
|
||||
const result = mapOfferings(answer);
|
||||
for (const pkg of result?.packages ?? []) {
|
||||
expect(Number.isInteger(pkg.price)).toBe(true);
|
||||
expect(pkg.price).toBeGreaterThan(0);
|
||||
expect(pkg.features.length).toBeGreaterThan(0);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
// Turns the answer of GET /api/v1/offerings (the CMS) into what the site
|
||||
// shows: the shoot packages (cards) and at most one banner. Pure functions, so
|
||||
// they are tested without a network. The build step (fetchOfferings.ts) uses
|
||||
// them; the site itself never calls the API (prices are in the HTML).
|
||||
//
|
||||
// Rule of the design: a bad answer never breaks the build and never leads to
|
||||
// an empty or wrong price. Anything that is not clearly valid is dropped, and
|
||||
// when no valid card is left the whole answer is rejected (null), so the
|
||||
// caller keeps the last known list (the snapshot).
|
||||
|
||||
export interface OfferingPackage {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number; // whole euros
|
||||
features: string[];
|
||||
priceNote?: string;
|
||||
description?: string;
|
||||
ctaLabel?: string;
|
||||
featured?: boolean;
|
||||
}
|
||||
|
||||
// Only the title is required: the banner hides every field that is empty
|
||||
export interface OfferingBanner {
|
||||
title: string;
|
||||
description?: string;
|
||||
priceText?: string;
|
||||
priceNote?: string;
|
||||
features: string[];
|
||||
ctaLabel?: string;
|
||||
}
|
||||
|
||||
export interface SiteOfferings {
|
||||
packages: OfferingPackage[];
|
||||
banner: OfferingBanner | null;
|
||||
}
|
||||
|
||||
const SLUG = /^[a-z0-9-]+$/;
|
||||
|
||||
// "€ 175", "€ 1.250", "175,-", "€ 175,00" → whole euros. Anything else
|
||||
// ("op aanvraag", "€ 12,50", "€ 0") has no usable price and gives null.
|
||||
export function parsePriceText(text: unknown): number | null {
|
||||
if (typeof text !== 'string') return null;
|
||||
const match = /^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$/.exec(
|
||||
text.trim(),
|
||||
);
|
||||
if (!match) return null;
|
||||
const euros = Number(match[1].replace(/\./g, ''));
|
||||
return Number.isInteger(euros) && euros > 0 ? euros : null;
|
||||
}
|
||||
|
||||
const asText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
||||
|
||||
function asFeatures(value: unknown): string[] | null {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const features = value.map(asText);
|
||||
return features.length > 0 && features.every((f) => f !== undefined)
|
||||
? (features as string[])
|
||||
: null;
|
||||
}
|
||||
|
||||
interface RawOffering {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const isObject = (value: unknown): value is RawOffering =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
function toPackage(raw: RawOffering): OfferingPackage | null {
|
||||
const id = asText(raw.slug);
|
||||
const name = asText(raw.title);
|
||||
const price = parsePriceText(raw.price);
|
||||
const features = asFeatures(raw.features);
|
||||
if (!id || !SLUG.test(id) || !name || price === null || !features) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
price,
|
||||
features,
|
||||
priceNote: asText(raw.priceNote),
|
||||
description: asText(raw.description),
|
||||
ctaLabel: asText(raw.ctaLabel),
|
||||
featured: raw.featured === true ? true : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function toBanner(raw: RawOffering): OfferingBanner | null {
|
||||
const title = asText(raw.title);
|
||||
if (!title) return null;
|
||||
return {
|
||||
title,
|
||||
description: asText(raw.description),
|
||||
priceText: asText(raw.price),
|
||||
priceNote: asText(raw.priceNote),
|
||||
features: asFeatures(raw.features) ?? [],
|
||||
ctaLabel: asText(raw.ctaLabel),
|
||||
};
|
||||
}
|
||||
|
||||
const orderOf = (raw: RawOffering) =>
|
||||
typeof raw.displayOrder === 'number' ? raw.displayOrder : 0;
|
||||
|
||||
// null: the answer cannot be used (not a list, or no valid card)
|
||||
export function mapOfferings(answer: unknown): SiteOfferings | null {
|
||||
if (!Array.isArray(answer)) return null;
|
||||
const rows = answer
|
||||
.filter(isObject)
|
||||
.map((raw, index) => ({ raw, index }))
|
||||
.sort((a, b) => orderOf(a.raw) - orderOf(b.raw) || a.index - b.index)
|
||||
.map(({ raw }) => raw);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const packages: OfferingPackage[] = [];
|
||||
let banner: OfferingBanner | null = null;
|
||||
for (const raw of rows) {
|
||||
if (raw.layout === 'banner') {
|
||||
// The CMS allows one banner per site; the first usable one wins
|
||||
banner ??= toBanner(raw);
|
||||
continue;
|
||||
}
|
||||
const pkg = toPackage(raw);
|
||||
if (!pkg || seen.has(pkg.id)) continue;
|
||||
seen.add(pkg.id);
|
||||
packages.push(pkg);
|
||||
}
|
||||
return packages.length > 0 ? { packages, banner } : null;
|
||||
}
|
||||
@@ -669,6 +669,9 @@ describe('startPreviewServer', () => {
|
||||
expect(
|
||||
(await ask(port, '/api/v1/contact-messages', 'POST')).status,
|
||||
).toBe(202);
|
||||
// Live pakketten: geen gegevens, zonder 404
|
||||
expect((await ask(port, '/api/v1/offerings')).status).toBe(204);
|
||||
expect((await ask(port, '/api/v1/offerings/banner')).status).toBe(204);
|
||||
// Al het andere blijft zoals het was
|
||||
expect((await ask(port, '/api/v1/andere')).status).toBe(404);
|
||||
expect((await ask(port, '/api/v1/contact-messages')).status).toBe(404);
|
||||
|
||||
@@ -217,6 +217,15 @@ export function contactStubResponse(
|
||||
captcha: null,
|
||||
});
|
||||
}
|
||||
// Live packages and banner: "no data" (204), so the page stays with the
|
||||
// baked list and shows no banner, without a 404 in the console (the site
|
||||
// asks once per page load)
|
||||
if (
|
||||
method === 'GET' &&
|
||||
(path === '/api/v1/offerings' || path === '/api/v1/offerings/banner')
|
||||
) {
|
||||
return { status: 204, body: '' };
|
||||
}
|
||||
if (method === 'POST' && path === CONTACT_API) {
|
||||
return json(202, { status: 'received' });
|
||||
}
|
||||
@@ -248,10 +257,12 @@ export function startPreviewServer(
|
||||
response,
|
||||
stub.status,
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
...(stub.body
|
||||
? { 'Content-Type': 'application/json' }
|
||||
: {}),
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
stub.body,
|
||||
stub.body || null,
|
||||
);
|
||||
request.resume();
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user