From 63153cfee3fd2cea503b14b3658207d02a0e9242 Mon Sep 17 00:00:00 2001 From: "Builder.io" Date: Mon, 29 Sep 2025 04:07:38 +0000 Subject: [PATCH] Add Builder CMS client helper cgen-0164ce382c7548628c12e74a6cb5f262 --- client/lib/builder.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 client/lib/builder.ts diff --git a/client/lib/builder.ts b/client/lib/builder.ts new file mode 100644 index 00000000..622cd030 --- /dev/null +++ b/client/lib/builder.ts @@ -0,0 +1,37 @@ +const API_ROOT = "https://cdn.builder.io/api/v3"; + +export type BuilderResult = { + results: Array<{ + id: string; + name?: string; + data?: T & { slug?: string; image?: string; category?: string; author?: string; date?: string; excerpt?: string; readTime?: string }; + url?: string; + published?: string; + }>; +}; + +export function getBuilderApiKey() { + return import.meta.env.VITE_BUILDER_API_KEY; +} + +export async function fetchBuilderList(model: string, opts: { limit?: number; query?: Record; fields?: string } = {}) { + const apiKey = getBuilderApiKey(); + if (!apiKey) throw new Error("Missing VITE_BUILDER_API_KEY"); + const params = new URLSearchParams({ apiKey }); + if (opts.limit) params.set("limit", String(opts.limit)); + if (opts.fields) params.set("fields", opts.fields); + if (opts.query) params.set("query", JSON.stringify(opts.query)); + const res = await fetch(`${API_ROOT}/content/${encodeURIComponent(model)}?${params.toString()}`); + if (!res.ok) throw new Error(`Builder fetch failed: ${res.status}`); + return (await res.json()) as BuilderResult; +} + +export async function fetchBuilderOne(model: string, slug: string) { + const apiKey = getBuilderApiKey(); + if (!apiKey) throw new Error("Missing VITE_BUILDER_API_KEY"); + const params = new URLSearchParams({ apiKey, limit: "1", query: JSON.stringify({ "data.slug": slug }) }); + const res = await fetch(`${API_ROOT}/content/${encodeURIComponent(model)}?${params.toString()}`); + if (!res.ok) throw new Error(`Builder fetch failed: ${res.status}`); + const json = (await res.json()) as BuilderResult; + return json.results?.[0] || null; +}