Files
vula-f731b6c5/src/lib/emdash.ts
T
Vula Builder 0dd831cefc Deploy
2026-06-04 09:16:59 +00:00

53 lines
2.0 KiB
TypeScript

// src/lib/emdash.ts — server-side CMS fetch helpers (do not import on client)
const EMDASH_URL = process.env.EMDASH_URL || 'http://localhost:4321'
const EMDASH_TOKEN = process.env.EMDASH_API_TOKEN || ''
export interface CmsItem {
id: string
slug: string
status: string
data: Record<string, unknown>
publishedAt: string | null
}
// emDash stores image fields as { provider, id, src } — flatten to plain URL strings.
function normalizeData(data: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(data)) {
out[k] = v && typeof v === 'object' && 'src' in v ? (v as { src: unknown }).src ?? v : v
}
return out
}
async function fetchCollection(collection: string, limit = 20): Promise<CmsItem[]> {
if (!EMDASH_TOKEN) return []
try {
const url = new URL(`/_emdash/api/content/${collection}`, EMDASH_URL)
url.searchParams.set('status', 'published')
url.searchParams.set('limit', String(limit))
const res = await fetch(url.toString(), {
headers: { Authorization: `Bearer ${EMDASH_TOKEN}` },
next: { revalidate: 60 },
})
if (!res.ok) return []
const json = await res.json() as { data?: { items?: CmsItem[] }; items?: CmsItem[] }
const items = json.data?.items ?? json.items ?? []
return items.map((item) => ({ ...item, data: normalizeData(item.data ?? {}) }))
} catch {
return []
}
}
export const getCampaigns = () => fetchCollection('campaigns')
export const getSpecials = () => fetchCollection('specials')
export const getBusinessHours = () => fetchCollection('business_hours', 1)
export const getPromotions = () => fetchCollection('promotions')
export const getFeaturedProductIds = async (): Promise<string[]> => {
const items = await fetchCollection('featured_products', 10)
return items.flatMap(i => {
const ids = i.data.product_ids
return Array.isArray(ids) ? ids as string[] : []
})
}
export const getBlogPosts = (limit = 10) => fetchCollection('posts', limit)