import type { GhostPost, GhostSettings } from './types.js'; export interface GhostClientOptions { ghostUrl: string; ghostApiKey: string; } function buildUrl(base: string, endpoint: string, params: Record): string { const url = new URL(endpoint, base); for (const [key, value] of Object.entries(params)) { url.searchParams.set(key, value); } return url.toString(); } export async function fetchSettings({ ghostUrl, ghostApiKey }: GhostClientOptions): Promise { const url = buildUrl(`${ghostUrl}/ghost/api/content/`, 'settings/', { key: ghostApiKey, }); const response = await fetch(url); if (!response.ok) { throw new Error(`Ghost settings fetch failed: ${response.status} ${response.statusText}`); } const data = (await response.json()) as { settings: GhostSettings }; return data.settings; } export async function fetchAllPosts({ ghostUrl, ghostApiKey }: GhostClientOptions): Promise { const posts: GhostPost[] = []; let page = 1; while (true) { const url = buildUrl(`${ghostUrl}/ghost/api/content/`, 'posts/', { key: ghostApiKey, include: 'authors,tags', formats: 'html,plaintext', limit: '100', page: String(page), }); const response = await fetch(url); if (!response.ok) { throw new Error(`Ghost posts fetch failed: ${response.status} ${response.statusText}`); } const data = (await response.json()) as { posts: GhostPost[]; meta?: { pagination?: { pages?: number } } }; if (!Array.isArray(data.posts) || data.posts.length === 0) { break; } posts.push(...data.posts); const totalPages = data.meta?.pagination?.pages ?? page; if (page >= totalPages) break; page++; } return posts; }