feat: serve site content from Appwrite TablesDB with .md fallback

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.
This commit is contained in:
spaghet committed 2026-11-26 19:29:31 -05:00
1 parent 2b775cbf99
commit 80577d6404
17 files changed
+871 -130

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# Copy to .env (gitignored; dotenv-cli loads it for dev/start/build).
#
# Content reads are PUBLIC — every Appwrite table grants read("any") — so the
# site works with none of these set. Defaults point at the homelab instance.
# Appwrite TablesDB content backend (src/lib/appwrite.ts)
# APPWRITE_ENDPOINT=https://appwrite.spaghet.io/v1
# APPWRITE_PROJECT_ID=homelab
# APPWRITE_DATABASE_ID=spaghet-home
# Optional: a server key sent with every read (bypasses the guest rate
# limiter). Needs only databases.read/collections.read/documents.read-style
# read scopes — see the spaghet-home-content key. Never exposed to the browser.
# APPWRITE_API_KEY=
*** In-process cache lifetime for content reads, seconds. On a failed refresh
# the stale value is served; a cold-cache failure falls back to the bundled
# .md copies under src/content.
# APPWRITE_CONTENT_TTL_SECONDS=60
# Uptime Kuma status page (src/lib/status.ts)
# STATUS_PAGE_URL=https://uptime.spaghet.io
# STATUS_PAGE_SLUG=public
+21 -1
View File
@@ -4,11 +4,31 @@ import sitemap from "@astrojs/sitemap"
import solidJs from "@astrojs/solid-js" import solidJs from "@astrojs/solid-js"
import node from "@astrojs/node" import node from "@astrojs/node"
import tailwindcss from "@tailwindcss/vite" import tailwindcss from "@tailwindcss/vite"
import { readdirSync } from "node:fs"
// The blog/projects/legal detail pages are served from Appwrite at request
// time (prerender = false), so they no longer appear in the build-time route
// list the sitemap integration collects. Compute their URLs from the bundled
// markdown copies — the same files scripts/appwrite-migrate.mjs imports, and
// the fallback source — so the sitemap stays complete without a build-time
// network call.
function contentPages() {
const site = "https://spaghet.io"
const slugs = (dir) =>
readdirSync(new URL(`./src/content/${dir}/`, import.meta.url))
.filter((f) => f.endsWith(".md"))
.map((f) => f.replace(/\.md$/, ""))
return [
...slugs("blog").map((s) => `${site}/blog/${s}/`),
...slugs("projects").map((s) => `${site}/projects/${s}/`),
...slugs("legal").map((s) => `${site}/legal/${s}/`),
]
}
// https://astro.build/config // https://astro.build/config
export default defineConfig({ export default defineConfig({
site: "https://spaghet.io", site: "https://spaghet.io",
integrations: [mdx(), sitemap(), solidJs()], integrations: [mdx(), sitemap({ customPages: contentPages() }), solidJs()],
output: "server", output: "server",
adapter: node({ mode: "ssr" }), adapter: node({ mode: "ssr" }),
markdown: { markdown: {
+42
View File
@@ -9,6 +9,7 @@
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@astrojs/check": "^0.9.10", "@astrojs/check": "^0.9.10",
"@astrojs/markdown-satteri": "^0.4.3",
"@astrojs/mdx": "^8.0.3", "@astrojs/mdx": "^8.0.3",
"@astrojs/node": "^11.1.7", "@astrojs/node": "^11.1.7",
"@astrojs/rss": "^4.0.19", "@astrojs/rss": "^4.0.19",
@@ -20,6 +21,7 @@
"astro": "^7.3.8", "astro": "^7.3.8",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"fuse.js": "^7.0.0", "fuse.js": "^7.0.0",
"node-appwrite": "^32.4.0",
"notenv": "^2.0.3", "notenv": "^2.0.3",
"rehype-stringify": "^10.0.1", "rehype-stringify": "^10.0.1",
"remark": "^15.0.1", "remark": "^15.0.1",
@@ -3246,6 +3248,15 @@
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
}, },
"node_modules/bignumber.js": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
"integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/boolbase": { "node_modules/boolbase": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
@@ -4324,6 +4335,15 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/json-bigint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
"license": "MIT",
"dependencies": {
"bignumber.js": "^9.0.0"
}
},
"node_modules/json-schema-traverse": { "node_modules/json-schema-traverse": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -5284,6 +5304,28 @@
"url": "https://opencollective.com/unified" "url": "https://opencollective.com/unified"
} }
}, },
"node_modules/node-appwrite": {
"version": "32.4.0",
"resolved": "https://registry.npmjs.org/node-appwrite/-/node-appwrite-32.4.0.tgz",
"integrity": "sha512-m+NeMSCpqE8Vfe6rBQvOnzL+X7aEahizG60I2TdKQK7jHzVIKnlhgOfSAW8z87/fi5qp/bks5GHC8kdpehsMjQ==",
"license": "BSD-3-Clause",
"dependencies": {
"json-bigint": "1.0.0",
"undici": "^6.27.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/node-appwrite/node_modules/undici": {
"version": "6.29.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/node-fetch-native": { "node_modules/node-fetch-native": {
"version": "1.6.7", "version": "1.6.7",
"resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",
+2
View File
@@ -17,6 +17,7 @@
}, },
"dependencies": { "dependencies": {
"@astrojs/check": "^0.9.10", "@astrojs/check": "^0.9.10",
"@astrojs/markdown-satteri": "^0.4.3",
"@astrojs/mdx": "^8.0.3", "@astrojs/mdx": "^8.0.3",
"@astrojs/node": "^11.1.7", "@astrojs/node": "^11.1.7",
"@astrojs/rss": "^4.0.19", "@astrojs/rss": "^4.0.19",
@@ -28,6 +29,7 @@
"astro": "^7.3.8", "astro": "^7.3.8",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"fuse.js": "^7.0.0", "fuse.js": "^7.0.0",
"node-appwrite": "^32.4.0",
"notenv": "^2.0.3", "notenv": "^2.0.3",
"rehype-stringify": "^10.0.1", "rehype-stringify": "^10.0.1",
"remark": "^15.0.1", "remark": "^15.0.1",
+217
View File
@@ -0,0 +1,217 @@
// src/lib/__tests__/appwrite.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest"
/**
* node-appwrite's Client captures its own fetch binding, so stubbing
* globalThis.fetch does not intercept it (a previous version of this file
* silently hit the live Appwrite). Instead the SDK is mocked at the module
* boundary: listRows/getRow become vi.fn()s returning the exact JSON shapes
* the tablesdb endpoints return (verified against the live instance), and the
* mapping, rendering, caching and fallback behavior under test is all ours.
* The wire contract itself is covered by scripts/appwrite-migrate.mjs and the
* live probes documented in the migration thread.
*/
const listRows = vi.fn()
const getRow = vi.fn()
vi.mock("node-appwrite", () => {
class AppwriteException extends Error {
code: number
type: string
constructor(message: string, code = 0, type = "") {
super(message)
this.code = code
this.type = type
}
}
return {
AppwriteException,
Client: class {
setEndpoint() { return this }
setProject() { return this }
setKey() { return this }
},
TablesDB: class {
listRows = listRows
getRow = getRow
},
Query: {
// Record the (attribute, op) pairs so tests can assert the queries we
// compose without coupling to the SDK's JSON encoding.
equal: (attribute: string, values: unknown) => ({ op: "equal", attribute, values }),
orderDesc: (attribute: string) => ({ op: "orderDesc", attribute }),
limit: (values: unknown) => ({ op: "limit", values }),
select: (values: unknown) => ({ op: "select", values }),
},
}
})
const {
listContent,
listSlim,
getContent,
listSearchEntries,
__resetCache,
} = await import("@lib/appwrite")
type FakeRow = Record<string, unknown> & { $id: string }
const BLOG_ROW: FakeRow = {
$id: "01-building-my-personal-website",
$sequence: "1",
$tableId: "blog",
$databaseId: "spaghet-home",
slug: "01-building-my-personal-website",
title: "Building My Personal Website",
summary: "A journey through creating my portfolio.",
// Exactly what a datetime column returns over the wire.
date: "2025-08-12T00:00:00.000+00:00",
tags: ["Astro", "Docker"],
draft: false,
template: "default",
featured: false,
content: "## The Concept\n\nSome **markdown** body.",
}
beforeEach(() => {
__resetCache()
listRows.mockReset()
getRow.mockReset()
})
describe("listContent", () => {
it("maps rows into the astro:content entry shape with rendered HTML", async () => {
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
const entries = await listContent("blog")
expect(entries).toHaveLength(1)
const entry = entries[0]
// Flat fields (what the article layouts read) plus `data` (PageLayout).
expect(entry.id).toBe("01-building-my-personal-website")
expect(entry.title).toBe("Building My Personal Website")
expect(entry.date).toBeInstanceOf(Date)
expect(entry.date.toISOString()).toBe("2025-08-12T00:00:00.000Z")
expect(entry.tags).toEqual(["Astro", "Docker"])
expect(entry.draft).toBe(false)
expect(entry.data.title).toBe("Building My Personal Website")
// content is rendered HTML, not raw markdown.
expect(entry.content).toContain("<h2")
expect(entry.content).toContain("<strong>markdown</strong>")
expect(entry.data.content).toBe(entry.content)
// The list query excludes drafts and orders newest-first on the date column.
const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[]
expect(queries.some((q) => q.op === "equal" && q.attribute === "draft")).toBe(true)
expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "date")).toBe(true)
})
it("work rows map company/role/dateStart/dateEnd", async () => {
listRows.mockResolvedValue({
total: 1,
rows: [{
$id: "09-chaplain-assistant",
slug: "09-chaplain-assistant",
company: "National Guard Bureau",
role: "Chaplain Assistant",
dateStart: "2007-12-01T00:00:00.000+00:00",
dateEnd: "2012-12-01T00:00:00.000+00:00",
content: "Body",
}],
})
const [entry] = await listContent("work")
expect(entry.company).toBe("National Guard Bureau")
expect(entry.dateStart).toBeInstanceOf(Date)
// work has no draft column; querying one would error.
const queries = listRows.mock.calls[0][0].queries as { op: string; attribute?: string }[]
expect(queries.some((q) => q.attribute === "draft")).toBe(false)
expect(queries.some((q) => q.op === "orderDesc" && q.attribute === "dateStart")).toBe(true)
})
it("caches within the TTL: a second call makes no request", async () => {
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
const first = await listContent("blog")
await listContent("blog")
expect(listRows).toHaveBeenCalledTimes(1)
expect(first).toHaveLength(1)
})
it("serves the stale cache when a refresh fails", async () => {
listRows.mockResolvedValue({ total: 1, rows: [BLOG_ROW] })
const first = await listContent("blog")
// Expire the entry by moving the clock past the default 60s TTL, then fail
// the refresh.
vi.useFakeTimers()
vi.setSystemTime(Date.now() + 61_000)
listRows.mockRejectedValue(new TypeError("fetch failed"))
const second = await listContent("blog")
vi.useRealTimers()
expect(second).toHaveLength(1)
expect(second[0].id).toBe(first[0].id)
})
it("throws when the cache is cold and Appwrite is down (caller falls back)", async () => {
listRows.mockRejectedValue(new TypeError("fetch failed"))
await expect(listContent("blog")).rejects.toThrow("fetch failed")
})
})
describe("getContent", () => {
it("returns the entry for a published slug", async () => {
getRow.mockResolvedValue(BLOG_ROW)
const entry = await getContent("blog", "01-building-my-personal-website")
expect(entry?.title).toBe("Building My Personal Website")
expect(entry?.content).toContain("<h2")
expect(getRow.mock.calls[0][0]).toMatchObject({
databaseId: "spaghet-home",
tableId: "blog",
rowId: "01-building-my-personal-website",
})
})
it("returns null on 404", async () => {
const { AppwriteException } = await import("node-appwrite")
getRow.mockRejectedValue(new AppwriteException("not found", 404, "row_not_found"))
expect(await getContent("blog", "nope")).toBeNull()
})
it("rethrows non-404 failures so the caller can fall back", async () => {
const { AppwriteException } = await import("node-appwrite")
getRow.mockRejectedValue(new AppwriteException("server error", 500))
await expect(getContent("blog", "x")).rejects.toThrow("server error")
})
it("returns null for a draft even when the row exists", async () => {
getRow.mockResolvedValue({ ...BLOG_ROW, draft: true })
expect(await getContent("blog", "01-building-my-personal-website")).toBeNull()
})
})
describe("listSlim", () => {
it("selects only the listing columns and keeps Date objects", async () => {
listRows.mockResolvedValue({ total: 1, rows: [{ ...BLOG_ROW, content: undefined }] })
const slim = await listSlim("blog")
const queries = listRows.mock.calls[0][0].queries as { op: string; values?: string[] }[]
const select = queries.find((q) => q.op === "select")
expect(select?.values).toContain("title")
expect(select?.values).not.toContain("content")
expect(slim[0].data.date).toBeInstanceOf(Date)
expect(slim[0].data.tags).toEqual(["Astro", "Docker"])
expect(slim[0].id).toBe(BLOG_ROW.$id)
})
})
describe("listSearchEntries", () => {
it("merges blog and projects with ISO dates and collection tags", async () => {
listRows.mockImplementation(({ tableId }: { tableId: string }) =>
Promise.resolve({
total: 1,
rows: [tableId === "blog"
? BLOG_ROW
: { ...BLOG_ROW, $id: "gitea", slug: "gitea", title: "Gitea" }],
})
)
const entries = await listSearchEntries()
expect(entries.map((e) => e.collection)).toEqual(["blog", "projects"])
expect(entries[0].date).toBe("2025-08-12T00:00:00.000Z")
expect(entries[1].slug).toBe("gitea")
})
})
+338
View File
@@ -0,0 +1,338 @@
/**
* Appwrite TablesDB content service.
*
* The site's content (blog posts, projects, work history, legal docs) lives in
* the `spaghet-home` database on appwrite.spaghet.io (project `homelab`), one
* table per collection, with the markdown body in the `content` column. This
* module fetches rows with the node-appwrite SDK, renders the markdown to HTML
* with Astro's own Sätteri pipeline (same Shiki dual-theme config as
* astro.config.mjs, so code blocks look identical to the old astro:content
* output), and maps rows into entry shapes that match what astro:content's
* glob loader used to hand the pages: `data` carries the typed frontmatter
* with dates as Date objects, and the same fields are spread flat on the entry
* for the article layouts (the old pages spread `...entry.data` themselves).
*
* Auth: reads are public — every table grants `read("any")`, so the server
* talks to Appwrite with only the project header and no secret. Set
* APPWRITE_API_KEY to send one anyway (bypasses the guest rate limiter on a
* busy deployment); it is never required and never reaches the browser.
*
* Resilience: every list/get is cached in-process for APPWRITE_CONTENT_TTL_SECONDS
* (default 60). On a failed refresh the stale value is served; if there is no
* cached value at all the error propagates and the caller (content-source.ts)
* falls back to the local .md copies via astro:content.
*/
import { AppwriteException, Client, Query, TablesDB } from "node-appwrite"
import { createSatteriMarkdownProcessor } from "@astrojs/markdown-satteri"
import type { MarkdownRenderer } from "@astrojs/internal-helpers/markdown"
import type { BlogPost, LegalDocument, Project, SearchEntry, WorkExperience } from "./types"
export const APPWRITE_ENDPOINT = process.env.APPWRITE_ENDPOINT ?? "https://appwrite.spaghet.io/v1"
export const APPWRITE_PROJECT_ID = process.env.APPWRITE_PROJECT_ID ?? "homelab"
export const APPWRITE_DATABASE_ID = process.env.APPWRITE_DATABASE_ID ?? "spaghet-home"
const TTL_MS = Number(process.env.APPWRITE_CONTENT_TTL_SECONDS ?? 60) * 1000
export type ContentTable = "blog" | "projects" | "work" | "legal"
/**
* Frontmatter with dates as Date, matching what the astro:content glob loader
* produced (its schema used z.date()). The types.ts shapes keep ISO strings
* because they mirror the raw frontmatter; the pages that call
* `.toISOString()` (search index, cards) rely on the Date form.
*/
export type BlogPostData = Omit<BlogPost, "date"> & { date: Date }
export type ProjectData = Omit<Project, "date"> & { date: Date }
export type WorkData = Omit<WorkExperience, "dateStart" | "dateEnd"> & { dateStart: Date; dateEnd: Date }
export type LegalData = Omit<LegalDocument, "date"> & { date: Date }
export interface TableDataMap {
blog: BlogPostData
projects: ProjectData
work: WorkData
legal: LegalData
}
/** An Appwrite row as it arrives over the wire (column bag plus $-metadata). */
type Row = Record<string, unknown> & { $id: string }
/**
* The entry shape the pages render: the typed fields spread flat (title,
* summary, date at the top level, as the article layouts expect from the old
* `...entry.data` spread), plus `data` for PageLayout props, and `content` as
* rendered HTML (what the old code took from entry.rendered.html).
*/
export type ContentEntry<K extends ContentTable = ContentTable> = {
id: string
collection: K
data: TableDataMap[K]
content: string
} & TableDataMap[K]
/** The slim listing shape (no body): cards, filters, search index, RSS. */
export interface SlimEntry {
id: string
collection: ContentTable
data: { title: string; summary: string; date: Date; tags: string[] }
}
let client: Client | undefined
function tables(): TablesDB {
if (!client) {
client = new Client().setEndpoint(APPWRITE_ENDPOINT).setProject(APPWRITE_PROJECT_ID)
const key = process.env.APPWRITE_API_KEY
if (key) client.setKey(key)
}
return new TablesDB(client)
}
// --- markdown rendering -------------------------------------------------
let renderer: Promise<MarkdownRenderer> | undefined
function getRenderer(): Promise<MarkdownRenderer> {
if (!renderer) {
// Mirrors astro.config.mjs `markdown.shikiConfig`: every token ships as a
// --shiki-light/--shiki-dark pair and global.css flips per mode.
renderer = createSatteriMarkdownProcessor({
syntaxHighlight: "shiki",
shikiConfig: {
themes: { light: "light-plus", dark: "everforest-dark" },
defaultColor: false,
},
})
}
return renderer
}
async function renderMarkdown(markdown: string): Promise<string> {
const result = await (await getRenderer()).render(markdown, { frontmatter: {} })
return result.code
}
// --- caching --------------------------------------------------------------
type CacheEntry = { at: number; value: unknown }
const cache = new Map<string, CacheEntry>()
const inflight = new Map<string, Promise<unknown>>()
/**
* Serve `load()` fresh (TTL_MS), dedupe concurrent calls onto one promise, and
* fall back to the last good value — however old — when the load fails. Only
* throws when there is nothing cached at all, i.e. a cold cache with Appwrite
* unreachable; content-source.ts turns that into the .md fallback.
*/
async function cached<T>(key: string, load: () => Promise<T>): Promise<T> {
const hit = cache.get(key)
if (hit && Date.now() - hit.at < TTL_MS) return hit.value as T
const running = inflight.get(key)
if (running) return running as Promise<T>
const promise = load()
.then((value) => {
cache.set(key, { at: Date.now(), value })
return value
})
.catch((err) => {
if (hit) {
console.warn(`[appwrite] refresh failed for ${key}; serving stale (${(err as Error).message})`)
return hit.value as T
}
throw err
})
.finally(() => inflight.delete(key))
inflight.set(key, promise)
return promise
}
// --- row -> entry mappers ---------------------------------------------------
function str(row: Row, key: string): string {
return String(row[key] ?? "")
}
function optStr(row: Row, key: string): string | undefined {
const v = row[key]
return typeof v === "string" && v !== "" ? v : undefined
}
function bool(row: Row, key: string): boolean {
return row[key] === true
}
function date(row: Row, key: string): Date {
// Appwrite datetime columns come back as e.g. "2025-08-12T00:00:00.000+00:00".
return new Date(str(row, key))
}
function tags(row: Row): string[] {
return Array.isArray(row.tags) ? (row.tags as string[]) : []
}
function toBlogPostData(row: Row): BlogPostData {
return {
id: row.$id,
title: str(row, "title"),
summary: str(row, "summary"),
date: date(row, "date"),
tags: tags(row),
draft: bool(row, "draft"),
content: "", // filled with rendered HTML below
template: str(row, "template") || "default",
featured: bool(row, "featured"),
}
}
function toProjectData(row: Row): ProjectData {
return {
id: row.$id,
title: str(row, "title"),
summary: str(row, "summary"),
date: date(row, "date"),
tags: tags(row),
draft: bool(row, "draft"),
content: "",
demoUrl: optStr(row, "demoUrl"),
repoUrl: optStr(row, "repoUrl"),
}
}
function toWorkData(row: Row): WorkData {
return {
id: row.$id,
company: str(row, "company"),
role: str(row, "role"),
dateStart: date(row, "dateStart"),
dateEnd: date(row, "dateEnd"),
content: "",
}
}
function toLegalData(row: Row): LegalData {
return {
id: row.$id,
title: str(row, "title"),
date: date(row, "date"),
content: "",
}
}
/**
* Build the flat page entry from a row. `content` starts as the RAW markdown;
* loadEntries renders it in place and returns the HTML.
*/
function rowToEntry<K extends ContentTable>(table: K, row: Row): ContentEntry<K> {
const data: TableDataMap[K] =
table === "blog" ? (toBlogPostData(row) as TableDataMap[K])
: table === "projects" ? (toProjectData(row) as TableDataMap[K])
: table === "work" ? (toWorkData(row) as TableDataMap[K])
: (toLegalData(row) as TableDataMap[K])
data.content = str(row, "content")
// `...data` first: its id/content are the same values restated below, and
// TS flags a literal key that a later spread would overwrite (ts 2783).
return { ...data, id: row.$id, collection: table, data, content: data.content } as ContentEntry<K>
}
async function loadEntries<K extends ContentTable>(table: K, rows: Row[]): Promise<ContentEntry<K>[]> {
const entries = rows.map((row) => rowToEntry(table, row))
// Render sequentially: the satteri/shiki pipeline initialises once and the
// payloads are small; 18 docs never justified a pool.
for (const entry of entries) {
entry.content = await renderMarkdown(entry.content)
entry.data.content = entry.content
}
return entries
}
// --- public API -------------------------------------------------------------
const LIST_ORDER: Record<ContentTable, string> = {
blog: "date",
projects: "date",
work: "dateStart",
legal: "date",
}
function listQueries(table: ContentTable, publishedOnly: boolean): ReturnType<typeof Query.orderDesc>[] {
const queries = [Query.orderDesc(LIST_ORDER[table]), Query.limit(100)]
// work/legal tables have no draft column; filtering on it would error.
if (publishedOnly && (table === "blog" || table === "projects")) {
queries.unshift(Query.equal("draft", false))
}
return queries as ReturnType<typeof Query.orderDesc>[]
}
/** Full entries (rendered HTML bodies), newest first. */
export function listContent<K extends ContentTable>(table: K, publishedOnly = true): Promise<ContentEntry<K>[]> {
return cached(`list:${table}:${publishedOnly}`, async () => {
const res = await tables().listRows({
databaseId: APPWRITE_DATABASE_ID,
tableId: table,
queries: listQueries(table, publishedOnly),
})
return loadEntries(table, res.rows as unknown as Row[])
})
}
/** Slim entries for listing cards, filters, the search index and RSS (no body). */
export function listSlim<K extends ContentTable>(table: K): Promise<(Omit<SlimEntry, "collection"> & { collection: K })[]> {
return cached(`slim:${table}`, async () => {
const res = await tables().listRows({
databaseId: APPWRITE_DATABASE_ID,
tableId: table,
queries: [
...listQueries(table, true),
Query.select(["slug", "title", "summary", "date", "tags"]),
],
})
return (res.rows as unknown as Row[]).map((row) => ({
id: row.$id,
collection: table as K,
data: {
title: str(row, "title"),
summary: str(row, "summary"),
date: date(row, "date"),
tags: tags(row),
},
}))
})
}
/** One published entry by slug, or null when missing/draft. */
export function getContent<K extends ContentTable>(table: K, slug: string): Promise<ContentEntry<K> | null> {
return cached(`get:${table}:${slug}`, async () => {
let row: Row
try {
row = (await tables().getRow({
databaseId: APPWRITE_DATABASE_ID,
tableId: table,
rowId: slug,
})) as unknown as Row
} catch (err) {
if (err instanceof AppwriteException && err.code === 404) return null
throw err
}
if (table === "blog" || table === "projects") {
if (bool(row, "draft")) return null
}
const [entry] = await loadEntries(table, [row])
return entry ?? null
})
}
/** The client-side fuse.js payload: blog + projects, slim, newest first. */
export async function listSearchEntries(): Promise<SearchEntry[]> {
const [blog, projects] = await Promise.all([listSlim("blog"), listSlim("projects")])
const toEntry = (e: SlimEntry): 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 [...blog.map(toEntry), ...projects.map(toEntry)]
}
/** Test helper: drop every cached value (and the client/renderer singletons). */
export function __resetCache(): void {
cache.clear()
inflight.clear()
client = undefined
renderer = undefined
}
+149
View File
@@ -0,0 +1,149 @@
/**
* 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)]
}
+4 -1
View File
@@ -29,7 +29,10 @@ export function byDateDesc(a: DatedEntry, b: DatedEntry): number {
* (home, blog, projects, search) emitting identical card props. * (home, blog, projects, search) emitting identical card props.
*/ */
export function toSearchEntry( export function toSearchEntry(
entry: CollectionEntry<"blog"> | CollectionEntry<"projects"> entry:
| CollectionEntry<"blog">
| CollectionEntry<"projects">
| { id: string; collection: "blog" | "projects"; data: { title: string; summary: string; date: Date; tags: string[] } }
): SearchEntry { ): SearchEntry {
return { return {
id: entry.id, id: entry.id,
+15 -20
View File
@@ -1,31 +1,26 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro" import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro" import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
import { getCollectionContent, getCollectionEntry } from "@lib/content-source"
export const prerender = true // Content comes from Appwrite at request time, so these pages can no longer be
// prerendered at build time; the node adapter serves them (output: "server" is
// already the default). A cold Appwrite falls back to the bundled .md copies
// (src/lib/content-source.ts), not to a 500.
export const prerender = false
export async function getStaticPaths() { const { slug } = Astro.params
const entries = await getCollection("blog", ({ data }) => !data.draft) const entry = slug ? await getCollectionEntry("blog", slug) : null
// The article layouts expect the flat BlogPost shape (title/summary/date at the if (!entry) return Astro.redirect("/blog")
// top level). Astro's collection entries nest frontmatter under `data`, so // The article layouts expect the flat BlogPost shape (title/summary/date at the
// spreading the entry alone left every article heading blank and made // top level); getCollectionEntry already spreads `data` onto the entry.
// formatDate(undefined) fall back to today's date. // ArticleBottomLayout derives prev/next from array position (index-1 = Prev),
const flat = entries.map((entry) => ({ // so it needs oldest-first — the reverse of the listContent default, and the
...entry, // same order the old filename-sorted getStaticPaths produced.
...entry.data, const allEntries = (await getCollectionContent("blog")).reverse()
content: entry.rendered?.html ?? "",
}))
return entries.map((entry, i) => ({
params: { slug: entry.id },
props: { entry: flat[i], allEntries: flat },
}))
}
const { entry, allEntries } = Astro.props
const { title, summary } = entry.data const { title, summary } = entry.data
--- ---
+12 -13
View File
@@ -1,26 +1,25 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import FilteredList from "@components/FilteredList" import FilteredList from "@components/FilteredList"
import { BLOG } from "@consts" import { BLOG } from "@consts"
import { byDateDesc } from "@lib/content"
import { parseFilterParams } from "@lib/filters" import { parseFilterParams } from "@lib/filters"
import { listSlimContent } from "@lib/content-source"
const entries = await getCollection("blog", ({ data }) => !data.draft)
// Only the fields the cards and the filters read. `content` was serialized into // Only the fields the cards and the filters read. `content` was serialized into
// the island's props on every request and never matched against — the markdown // the island's props on every request and never matched against — the markdown
// body is the single largest thing on this page. // body is the single largest thing on this page. Appwrite TablesDB first,
const posts = entries // bundled .md fallback (src/lib/content-source.ts); ordering is already
.sort(byDateDesc) // newest-first with the byDateDesc tie-break.
.map((entry) => ({ const slim = await listSlimContent("blog")
id: entry.id, const posts = slim.map((entry) => ({
title: entry.data.title, id: entry.id,
summary: entry.data.summary, title: entry.data.title,
date: entry.data.date.toISOString(), summary: entry.data.summary,
tags: entry.data.tags, date: entry.data.date.toISOString(),
})) tags: entry.data.tags,
}))
// Frontmatter runs on the server, so the initial filter state has to come from // Frontmatter runs on the server, so the initial filter state has to come from
// the request URL rather than `window.location` (see src/pages/search/index.astro). // the request URL rather than `window.location` (see src/pages/search/index.astro).
+9 -12
View File
@@ -1,24 +1,21 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import ArrowCard from "@components/ArrowCard" import ArrowCard from "@components/ArrowCard"
import StackCard from "@components/StackCard.astro" import StackCard from "@components/StackCard.astro"
import { SITE, SOCIALS } from "@consts" import { SITE, SOCIALS } from "@consts"
import { byDateDesc, toSearchEntry } from "@lib/content" import { toSearchEntry } from "@lib/content"
import { listSlimContent } from "@lib/content-source"
import ParmesanFlecks from "@components/ParmesanFlecks.astro" import ParmesanFlecks from "@components/ParmesanFlecks.astro"
import MeatballShower from "@components/MeatballShower.astro" import MeatballShower from "@components/MeatballShower.astro"
const allBlogEntries = await getCollection("blog", ({ data }) => !data.draft) // Appwrite TablesDB first, bundled .md fallback (src/lib/content-source.ts).
const posts = allBlogEntries // listSlimContent already returns published entries newest-first with the
.sort(byDateDesc) // byDateDesc tie-break, so no local sort is needed here.
.slice(0, 3) const blogSlim = await listSlimContent("blog")
.map(toSearchEntry) const posts = blogSlim.slice(0, 3).map(toSearchEntry)
const allProjectEntries = await getCollection("projects", ({ data }) => !data.draft) const projectSlim = await listSlimContent("projects")
const projects = allProjectEntries const projects = projectSlim.slice(0, 3).map(toSearchEntry)
.sort(byDateDesc)
.slice(0, 3)
.map(toSearchEntry)
const stack = [ const stack = [
{ {
+6 -13
View File
@@ -1,22 +1,15 @@
--- ---
export const prerender = true; export const prerender = false;
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import { formatDate } from "@lib/utils" import { formatDate } from "@lib/utils"
import { SITE } from "@consts" import { SITE } from "@consts"
import { getCollectionEntry } from "@lib/content-source"
export async function getStaticPaths() { const { slug } = Astro.params
const entries = await getCollection("legal") const doc = slug ? await getCollectionEntry("legal", slug) : null
return entries.map((entry) => ({ if (!doc) return Astro.redirect("/")
params: { slug: entry.id },
props: { entry },
}))
}
const { entry } = Astro.props
const doc = entry
--- ---
<PageLayout title={doc.data.title} description={`${doc.data.title} for ${SITE.TITLE}`}> <PageLayout title={doc.data.title} description={`${doc.data.title} for ${SITE.TITLE}`}>
@@ -31,6 +24,6 @@ const doc = entry
</div> </div>
</TopLayout> </TopLayout>
<BottomLayout> <BottomLayout>
<article class="animate prose dark:prose-invert text-ink" set:html={doc.rendered?.html}></article> <article class="animate prose dark:prose-invert text-ink" set:html={doc.content}></article>
</BottomLayout> </BottomLayout>
</PageLayout> </PageLayout>
+8 -18
View File
@@ -1,29 +1,19 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro" import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro" import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
import { getCollectionContent, getCollectionEntry } from "@lib/content-source"
export const prerender = true // Content comes from Appwrite at request time; see the note in
// src/pages/blog/[...slug].astro.
export const prerender = false
export async function getStaticPaths() { const { slug } = Astro.params
const entries = await getCollection("projects", ({ data }) => !data.draft) const entry = slug ? await getCollectionEntry("projects", slug) : null
// Flatten frontmatter to the shape ArticleTopLayout/ArticleBottomLayout expect; if (!entry) return Astro.redirect("/projects")
// see the note in src/pages/blog/[...slug].astro. const allEntries = (await getCollectionContent("projects")).reverse()
const flat = entries.map((entry) => ({
...entry,
...entry.data,
content: entry.rendered?.html ?? "",
}))
return entries.map((entry, i) => ({
params: { slug: entry.id },
props: { entry: flat[i], allEntries: flat },
}))
}
const { entry, allEntries } = Astro.props
const { title, summary } = entry.data const { title, summary } = entry.data
--- ---
+9 -12
View File
@@ -1,24 +1,21 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import FilteredList from "@components/FilteredList" import FilteredList from "@components/FilteredList"
import { PROJECTS } from "@consts" import { PROJECTS } from "@consts"
import { byDateDesc } from "@lib/content"
import { parseFilterParams } from "@lib/filters" import { parseFilterParams } from "@lib/filters"
import { listSlimContent } from "@lib/content-source"
const entries = await getCollection("projects", ({ data }) => !data.draft)
// Only the fields the cards and the filters read; see src/pages/blog/index.astro. // Only the fields the cards and the filters read; see src/pages/blog/index.astro.
const projects = entries const slim = await listSlimContent("projects")
.sort(byDateDesc) const projects = slim.map((entry) => ({
.map((entry) => ({ id: entry.id,
id: entry.id, title: entry.data.title,
title: entry.data.title, summary: entry.data.summary,
summary: entry.data.summary, date: entry.data.date.toISOString(),
date: entry.data.date.toISOString(), tags: entry.data.tags,
tags: entry.data.tags, }))
}))
// Frontmatter runs on the server, so the initial filter state has to come from // Frontmatter runs on the server, so the initial filter state has to come from
// the request URL rather than `window.location` (see src/pages/search/index.astro). // the request URL rather than `window.location` (see src/pages/search/index.astro).
+9 -10
View File
@@ -1,22 +1,21 @@
import rss from "@astrojs/rss" import rss from "@astrojs/rss"
import { getCollection } from "astro:content"
import { SITE } from "@consts" import { SITE } from "@consts"
import { listSlimContent } from "@lib/content-source"
type Context = { type Context = {
site: string site: string
} }
export async function GET(context: Context) { export async function GET(context: Context) {
const entries = await getCollection("blog", ({ data }) => !data.draft) // Published posts, newest first (listSlimContent ordering).
const entries = await listSlimContent("blog")
const items = entries const items = entries.map((entry) => ({
.sort((a, b) => b.data.date.getTime() - a.data.date.getTime()) title: entry.data.title,
.map((entry) => ({ description: entry.data.summary,
title: entry.data.title, pubDate: entry.data.date,
description: entry.data.summary, link: `/blog/${entry.id}/`,
pubDate: entry.data.date, }))
link: `/blog/${entry.id}/`,
}))
return rss({ return rss({
title: SITE.TITLE, title: SITE.TITLE,
+4 -27
View File
@@ -1,38 +1,15 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import Search from "@components/Search" import Search from "@components/Search"
import { SEARCH } from "@consts" import { SEARCH } from "@consts"
import type { SearchEntry } from "@lib/search" import type { SearchEntry } from "@lib/search"
import { getSearchEntries } from "@lib/content-source"
// Blog posts -> slim searchable entries. // Blog + projects -> slim searchable entries (fuse.js runs in the browser;
// `body` is intentionally NOT serialized to the client; see src/lib/search.ts. // `body` is intentionally NOT serialized to the client, see src/lib/search.ts).
const blogEntries = await getCollection("blog", ({ data }) => !data.draft) const entries: SearchEntry[] = await getSearchEntries()
const posts: SearchEntry[] = blogEntries.map((entry) => ({
id: entry.id,
slug: entry.id,
collection: "blog",
title: entry.data.title,
summary: entry.data.summary,
date: entry.data.date.toISOString(),
tags: entry.data.tags,
}))
// Projects -> slim searchable entries.
const projectEntries = await getCollection("projects", ({ data }) => !data.draft)
const projects: SearchEntry[] = projectEntries.map((entry) => ({
id: entry.id,
slug: entry.id,
collection: "projects",
title: entry.data.title,
summary: entry.data.summary,
date: entry.data.date.toISOString(),
tags: entry.data.tags,
}))
const entries: SearchEntry[] = [...posts, ...projects]
// Read the `?search=` param from the incoming SSR request. // Read the `?search=` param from the incoming SSR request.
// NOTE: this frontmatter runs on the server, so `window` is never available // NOTE: this frontmatter runs on the server, so `window` is never available
+3 -3
View File
@@ -1,11 +1,11 @@
--- ---
import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro" import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro" import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro" import BottomLayout from "@layouts/BottomLayout.astro"
import { WORK } from "@consts" import { WORK } from "@consts"
import { getCollectionContent } from "@lib/content-source"
const work = await getCollection("work") const work = await getCollectionContent("work")
function formatWorkDate(input: Date | string) { function formatWorkDate(input: Date | string) {
if (typeof input === "string") input = new Date(input) if (typeof input === "string") input = new Date(input)
@@ -39,7 +39,7 @@ function formatWorkDate(input: Date | string) {
<div class="text-sm font-semibold text-accent"> <div class="text-sm font-semibold text-accent">
{entry.data.role} {entry.data.role}
</div> </div>
<article class="prose dark:prose-invert text-ink" set:html={entry.rendered?.html}></article> <article class="prose dark:prose-invert text-ink" set:html={entry.content}></article>
</li> </li>
)) ))
} }