Files
AndreaSlopFotografie/web/config/fetchOfferings.ts
T
SluijsensandClaude Sonnet 5.5 5bfbde1881 Reads the shoot packages and an optional banner from the CMS at build time
The build asks GET /api/v1/offerings and bakes the packages into the pages,
with a committed snapshot as fallback so a CMS outage never breaks the build
or shows an empty price. The form choices and ?pakket= use the same list. An
offering with layout=banner becomes an optional band under the price cards.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:13:01 +01:00

70 lines
2.6 KiB
TypeScript

// Build step, runs before the build: asks the CMS for the shoot packages and
// writes src/content/offerings.generated.json, which the site imports. With
// no address, a failing CMS or an unusable answer the committed snapshot
// (src/content/offerings.snapshot.json) is used, so the build never fails
// and never shows empty prices. The log says which one was used.
//
// OFFERINGS_URL: the site's own address that serves the API, for example
// 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';
const SNAPSHOT = fileURLToPath(
new URL('../src/content/offerings.snapshot.json', import.meta.url),
);
const GENERATED = fileURLToPath(
new URL('../src/content/offerings.generated.json', import.meta.url),
);
const TIMEOUT_MS = 10_000;
const ATTEMPTS = 2;
async function fetchAnswer(base: string): Promise<unknown> {
const url = new URL('/api/v1/offerings', base);
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`status ${response.status}`);
return await response.json();
} catch (error) {
if (attempt >= ATTEMPTS) throw error;
}
}
}
async function main() {
const snapshot = JSON.parse(
readFileSync(SNAPSHOT, 'utf8'),
) as SiteOfferings;
const base = process.env.OFFERINGS_URL?.trim();
let result = { ...snapshot, source: 'snapshot' };
if (!base) {
console.log('[offerings] no OFFERINGS_URL: using the snapshot');
} else {
try {
const mapped = mapOfferings(await fetchAnswer(base));
if (mapped) {
result = { ...mapped, source: 'cms' };
console.log(
`[offerings] ${mapped.packages.length} packages` +
`${mapped.banner ? ' and a banner' : ''} from ${base}`,
);
} else {
console.warn(
`[offerings] answer of ${base} has no valid package: using the snapshot`,
);
}
} catch (error) {
console.warn(
`[offerings] ${base} not reachable (${String(error)}): using the snapshot`,
);
}
}
writeFileSync(GENERATED, JSON.stringify(result, null, 4) + '\n');
}
await main();