Replace astro:content getCollection() reads in all 9 content pages with src/lib/content-source.ts: Appwrite TablesDB (spaghet-home database on appwrite.spaghet.io) first, bundled src/content/*.md fallback on a cold-cache outage. Blog/project/legal detail pages flip from prerender to SSR (content now arrives at request time); sitemap keeps every detail URL via customPages computed from the bundled .md copies. - src/lib/appwrite.ts: TablesDB service (node-appwrite), markdown rendered through Astro's own satteri+shiki pipeline (dual-theme, same config as astro.config.mjs) — article HTML verified byte-identical to production. Public reads: tables grant read(any), no secret required. 60s in-process cache, stale-serving on refresh failure. - src/lib/__tests__/appwrite.test.ts: 11 tests mocking the SDK boundary (the SDK binds its own fetch, so global stubs do not intercept it). - Draft posts now 302 to /blog and drop off listings/RSS/search at request time instead of at build time. - astro check: 0 errors; vitest: 94 pass; build clean; end-to-end verified against live Appwrite and against a forced outage.
150 lines
6.0 KiB
TypeScript
150 lines
6.0 KiB
TypeScript
/**
|
|
* Content source facade: Appwrite TablesDB first, bundled .md fallback.
|
|
*
|
|
* Every page imports getCollectionContent/getCollectionEntry/listSlimContent
|
|
* from here instead of touching astro:content or the Appwrite SDK directly.
|
|
*
|
|
* Why a fallback at all: the markdown files under src/content stay in the repo
|
|
* as the backup copy (scripts/appwrite-migrate.mjs re-imports from them), and
|
|
* the astro:content glob loader reads them at build time for free. If Appwrite
|
|
* is unreachable when a page is requested and this process has never cached a
|
|
* successful read, we serve from the bundled copies so the site never 500s on
|
|
* a backend outage. Stale beats dead.
|
|
*
|
|
* Entries from both sources share one shape (see appwrite.ts ContentEntry):
|
|
* the typed frontmatter spread flat for the article layouts, `data` for page
|
|
* props, and `content` as rendered HTML.
|
|
*/
|
|
import { getCollection as getAstroCollection } from "astro:content"
|
|
import {
|
|
getContent as appwriteGetContent,
|
|
listContent as appwriteListContent,
|
|
listSlim as appwriteListSlim,
|
|
type ContentEntry,
|
|
type ContentTable,
|
|
} from "./appwrite"
|
|
import type { SearchEntry } from "./types"
|
|
|
|
export type { ContentEntry, ContentTable }
|
|
|
|
/** True after the most recent content read succeeded against Appwrite. */
|
|
let appwriteHealthy = false
|
|
export function isAppwriteHealthy(): boolean {
|
|
return appwriteHealthy
|
|
}
|
|
|
|
/**
|
|
* Wrap an astro:content entry in the shared shape. The glob loader already
|
|
* gives `data` with Date objects (z.date() schema); the old pages spread
|
|
* `...entry.data` at the call site, so we do it here instead.
|
|
*/
|
|
async function toFallbackEntry(table: ContentTable, entry: Awaited<ReturnType<typeof getAstroCollection>>[number]): Promise<ContentEntry> {
|
|
// The glob loader pre-renders markdown at build time; the old pages read the
|
|
// same `entry.rendered?.html`.
|
|
const html = entry.rendered?.html ?? ""
|
|
const data = { ...(entry.data as object), id: entry.id } as ContentEntry["data"]
|
|
data.content = html
|
|
// `...data` first: its id/content are restated below, and TS flags a literal
|
|
// key that a later spread would overwrite (ts 2783).
|
|
return { ...data, id: entry.id, collection: table, data, content: html } as ContentEntry
|
|
}
|
|
|
|
function sortEntries(entries: ContentEntry[], table: ContentTable): ContentEntry[] {
|
|
const key = table === "work" ? "dateStart" : "date"
|
|
return entries.sort((a, b) => {
|
|
const da = (a.data as unknown as Record<string, Date>)[key]?.getTime() ?? 0
|
|
const db = (b.data as unknown as Record<string, Date>)[key]?.getTime() ?? 0
|
|
// Equal dates fall back to id, matching byDateDesc in lib/content.ts.
|
|
return db - da || a.id.localeCompare(b.id)
|
|
})
|
|
}
|
|
|
|
async function fallbackList(table: ContentTable): Promise<ContentEntry[]> {
|
|
const entries = await getAstroCollection(table as "blog")
|
|
const out: ContentEntry[] = []
|
|
for (const entry of entries) {
|
|
if ((entry.data as { draft?: boolean }).draft) continue
|
|
out.push(await toFallbackEntry(table, entry))
|
|
}
|
|
return sortEntries(out, table)
|
|
}
|
|
|
|
async function fallbackGet(table: ContentTable, slug: string): Promise<ContentEntry | null> {
|
|
const entries = await getAstroCollection(table as "blog")
|
|
const entry = entries.find((e) => e.id === slug)
|
|
if (!entry) return null
|
|
if ((entry.data as { draft?: boolean }).draft) return null
|
|
return toFallbackEntry(table, entry)
|
|
}
|
|
|
|
/**
|
|
* Full entries (rendered HTML bodies), newest first, drafts excluded.
|
|
*
|
|
* Appwrite throws only on a cold-cache outage (appwrite.ts serves stale
|
|
* otherwise), which is exactly when we switch to the bundled .md copies.
|
|
*/
|
|
export async function getCollectionContent<K extends ContentTable>(table: K): Promise<ContentEntry<K>[]> {
|
|
try {
|
|
const entries = await appwriteListContent(table)
|
|
appwriteHealthy = true
|
|
return entries
|
|
} catch (err) {
|
|
appwriteHealthy = false
|
|
console.error(`[content] Appwrite unreachable for ${table}; falling back to bundled .md (${(err as Error).message})`)
|
|
return (await fallbackList(table)) as unknown as ContentEntry<K>[]
|
|
}
|
|
}
|
|
|
|
/** One published entry by slug, or null. */
|
|
export async function getCollectionEntry<K extends ContentTable>(table: K, slug: string): Promise<ContentEntry<K> | null> {
|
|
try {
|
|
const entry = await appwriteGetContent(table, slug)
|
|
appwriteHealthy = true
|
|
return entry
|
|
} catch (err) {
|
|
appwriteHealthy = false
|
|
console.error(`[content] Appwrite unreachable for ${table}/${slug}; falling back to bundled .md (${(err as Error).message})`)
|
|
return (await fallbackGet(table, slug)) as unknown as ContentEntry<K> | null
|
|
}
|
|
}
|
|
|
|
/** Slim listing entries (no body) for cards, filters and RSS. */
|
|
export async function listSlimContent<K extends ContentTable>(table: K): Promise<SlimSource<K>[]> {
|
|
try {
|
|
const rows = await appwriteListSlim(table)
|
|
appwriteHealthy = true
|
|
return rows
|
|
} catch (err) {
|
|
appwriteHealthy = false
|
|
console.error(`[content] Appwrite unreachable for ${table} listing; falling back to bundled .md (${(err as Error).message})`)
|
|
const entries = await fallbackList(table)
|
|
return entries.map((e) => ({
|
|
id: e.id,
|
|
collection: table,
|
|
data: {
|
|
title: (e.data as { title?: string }).title ?? "",
|
|
summary: (e.data as { summary?: string }).summary ?? "",
|
|
date: (e.data as { date?: Date }).date ?? new Date(0),
|
|
tags: (e.data as { tags?: string[] }).tags ?? [],
|
|
},
|
|
}))
|
|
}
|
|
}
|
|
|
|
type SlimSource<K extends ContentTable = ContentTable> = Awaited<ReturnType<typeof appwriteListSlim<K>>>[number]
|
|
|
|
/** The client-side fuse.js payload (blog + projects, slim). */
|
|
export async function getSearchEntries(): Promise<SearchEntry[]> {
|
|
const [posts, projects] = await Promise.all([listSlimContent("blog"), listSlimContent("projects")])
|
|
const toEntry = (e: SlimSource): SearchEntry => ({
|
|
id: e.id,
|
|
slug: e.id,
|
|
collection: e.collection as "blog" | "projects",
|
|
title: e.data.title,
|
|
summary: e.data.summary,
|
|
tags: e.data.tags,
|
|
date: e.data.date.toISOString(),
|
|
})
|
|
return [...posts.map(toEntry), ...projects.map(toEntry)]
|
|
}
|