Add a blog: posts at /blog/:id and a Community page section

Admin → Blog → Posts (migration 031): our own posts with a
content-block body, cover image, excerpt, date, tags, and authors
shown as person tiles, either People records or a guest name and
photo. A post is a draft until published; Listed works as it does
elsewhere. Posts are on the QR page too.

Admin → Blog → Community section: the first section of the
Community page, with its heading and blurb from the admin, in two
halves, each pinned first and then newest up to its slots. Our posts
come from blog_posts; community posts are pinned link or video cards
(reusing featured cards and Fetch preview), then the newest items
from a list of RSS or Atom feeds. Feeds are read through the link
preview's guarded fetch and cached for 30 minutes, and a failing feed
keeps its last good items.

content_blocks and featured_cards are rebuilt to accept the new owner
kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 16:27:00 -05:00
parent d4f65d93b4
commit d374f9ac17
21 changed files with 1275 additions and 15 deletions

View file

@ -799,6 +799,96 @@ const frontPage = {
],
};
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts of our own, with a content-block body and people as
authors, and the Community page's blog section, a singleton like
the front page. The section's community posts are featured cards
owned by 'community_page'. ─────────────────────────────────── */
const blogPosts = {
key: "blog_posts",
table: "blog_posts",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
list: {
columns: ["id", "title", "published_on", "tags", "is_published", "is_listed", "updated_at"],
filters: ["is_published", "is_listed"],
search: ["title", "id", "tags"],
order: "published_on IS NULL, published_on DESC, title",
},
columns: [
text("title", { required: true }),
text("excerpt"),
text("cover_image"),
date("published_on"),
text("tags"),
text("guest_author"),
text("guest_photo"),
bool("is_published"),
bool("is_listed"),
],
children: [
{
key: "authors",
table: "blog_post_authors",
owner: { column: "post_id" },
order: "sort_order",
columns: [text("person_id", { required: true })],
},
blocksChild("blog_post"),
],
};
const communityPage = {
key: "community_page",
table: "community_page",
idColumn: "id",
idKind: "slug",
singleton: "community",
concurrency: "updated_at",
list: {
columns: ["id", "blog_title", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
text("blog_title"),
text("blog_blurb"),
text("internal_title"),
int("internal_slots"),
text("external_title"),
int("external_slots"),
text("external_url"),
text("external_label"),
],
children: [
{
key: "pinned_posts",
table: "community_page_pinned_posts",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("post_id", { required: true })],
},
featuredCardsChild("community_page"),
{
key: "feeds",
table: "community_page_feeds",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("url", { required: true }), text("label")],
},
],
};
export const ENTITIES = {
organizations,
events,
@ -807,6 +897,8 @@ export const ENTITIES = {
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
};
/* ── Options for the form's select inputs ────────────────────── */
@ -819,6 +911,7 @@ export const OPTION_QUERIES = {
event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order",
events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title",
people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name",
blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title",
// org_id rides along so the affiliation row can filter the list
// down to teams of the organization it already names.

150
server/src/feeds.js Normal file
View file

@ -0,0 +1,150 @@
/* ═══════════════════════════════════════════════════════════════
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets
the same public-address checks, timeout and size cap as a link
preview. Results are kept in memory for CACHE_MS. A feed that
fails keeps serving what it last returned, and one that has never
worked contributes nothing: the section shows the pinned posts
and whatever the other feeds have, rather than an error.
Items come back as plain data: title, url, excerpt, image,
published (ISO), source. Only http(s) links and https images are
kept, so a feed can't put a javascript: link or a mixed-content
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
const MAX_ITEMS_PER_FEED = 20;
const EXCERPT_CHARS = 300;
const cache = new Map(); // url → { at, feed }
/* ── Parsing ───────────────────────────────────────────────── */
function unwrap(text) {
return text.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1");
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). */
function inner(xml, tag) {
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
return match ? unwrap(match[1]) : null;
}
function attrOf(xml, tag, name, where = () => true) {
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
const el = match[0];
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
function plain(html) {
if (!html) return null;
const text = decodeEntities(html.replace(/<[^>]+>/g, " "));
if (!text) return null;
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
}
function safeUrl(raw, base, { httpsOnly = false } = {}) {
if (!raw) return null;
try {
const url = new URL(decodeEntities(raw), base);
if (url.protocol === "https:" || (!httpsOnly && url.protocol === "http:")) return url.toString();
} catch {
/* not a URL */
}
return null;
}
function isoDate(raw) {
if (!raw) return null;
const date = new Date(raw.trim());
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
function firstImage(html) {
return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null;
}
function parseFeed(xml, feedUrl) {
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
const items = [];
for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) {
const link = isAtom
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
: inner(block, "link");
const url = safeUrl(link?.trim(), feedUrl);
const title = decodeEntities(inner(block, "title") ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
const summary = inner(block, "description") ?? inner(block, "summary");
const image =
attrOf(block, "enclosure", "url", (el) => /type\s*=\s*["']image\//i.test(el)) ??
attrOf(block, "media:content", "url") ??
attrOf(block, "media:thumbnail", "url") ??
firstImage(body) ??
firstImage(summary);
items.push({
title,
url,
excerpt: plain(summary) ?? plain(body),
image: safeUrl(image, feedUrl, { httpsOnly: true }),
published: isoDate(inner(block, "pubDate") ?? inner(block, "published") ?? inner(block, "updated")),
});
}
return { title: channelTitle || null, items };
}
/* ── Fetching ──────────────────────────────────────────────── */
async function fetchFeed(url) {
const result = await safeGet(url, {
maxBytes: MAX_FEED_BYTES,
accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.1",
});
return parseFeed(result.body.toString("utf8"), result.url.toString());
}
async function readFeed(url) {
const hit = cache.get(url);
if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed;
try {
const feed = await fetchFeed(url);
cache.set(url, { at: Date.now(), feed });
return feed;
} catch (err) {
console.warn(`feed ${url}: ${err.message}`);
// Serve the last good copy, and don't retry on every request.
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
}
}
/* Every listed feed's items, newest first, each tagged with its
source: the row's label, else the feed's own title. */
export async function readFeeds(rows) {
const feeds = await Promise.all(rows.map((row) => readFeed(row.url)));
const items = feeds.flatMap((feed, i) =>
feed.items.map((item) => ({ ...item, source: rows[i].label || feed.title })),
);
return items.sort((a, b) => (b.published ?? "").localeCompare(a.published ?? ""));
}

View file

@ -22,6 +22,7 @@ import people from "./routes/people.js";
import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import feedback from "./routes/feedback.js";
import auth from "./routes/auth.js";
import admin from "./routes/admin.js";
@ -67,6 +68,7 @@ app.route("/api", people);
app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));

View file

@ -22,7 +22,8 @@
· TIMEOUT_MS per request, and at most MAX_HTML_BYTES of page
or MAX_UPLOAD_BYTES of image is read
Editors and up only (routes/media.js).
Editors and up only (routes/media.js). feeds.js reads RSS
through the same safeGet.
═══════════════════════════════════════════════════════════════ */
import { lookup } from "node:dns/promises";
@ -102,7 +103,7 @@ async function vet(raw) {
/* ── One request, pinned to the vetted address ─────────────── */
function requestOnce({ url, address }, { maxBytes, accept }) {
function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) {
const client = url.protocol === "https:" ? https : http;
return new Promise((resolve, reject) => {
@ -140,7 +141,7 @@ function requestOnce({ url, address }, { maxBytes, accept }) {
// A page's head is at the top; stop reading and use what
// arrived. An image that's too big is refused outright.
res.destroy();
if (accept.startsWith("text/html")) {
if (truncate) {
resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" });
} else {
reject(new MediaError(413, "The preview image is too large."));
@ -163,7 +164,8 @@ function requestOnce({ url, address }, { maxBytes, accept }) {
});
}
async function safeGet(raw, options) {
/* Also used by feeds.js, so feeds get the same address checks. */
export async function safeGet(raw, options) {
let next = raw;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const target = await vet(next);
@ -178,7 +180,7 @@ async function safeGet(raw, options) {
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
function decode(text) {
export function decodeEntities(text) {
return text
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
@ -197,11 +199,11 @@ function readMeta(html) {
for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) {
const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase();
const content = attr(tag, "content");
if (key && content != null && !(key in meta)) meta[key] = decode(content);
if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content);
}
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1];
return {
title: meta["og:title"] || meta["twitter:title"] || (title ? decode(title) : null) || null,
title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null,
description:
meta["og:description"] || meta["twitter:description"] || meta.description || null,
image: meta["og:image:secure_url"] || meta["og:image"] || meta["twitter:image"] || null,
@ -212,6 +214,7 @@ function readMeta(html) {
export async function previewLink(raw) {
const page = await safeGet(raw, {
maxBytes: MAX_HTML_BYTES,
truncate: true,
accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1",
});
if (!/html/i.test(page.type)) {

View file

@ -0,0 +1,254 @@
-- ═══════════════════════════════════════════════════════════════
-- 031 BLOG
--
-- Posts of our own, at /blog/<id>, and the Community page's blog
-- section, which shows two subsections:
--
-- Our posts pinned blog_posts first, then the newest
-- published, listed ones, up to internal_slots
-- Community posts pinned featured_cards (owner 'community_page')
-- first, then the newest items from the RSS or
-- Atom feeds in community_page_feeds, up to
-- external_slots
--
-- blog_posts
-- A draft until published (is_published defaults to 0, as for
-- people): a half-written post shouldn't go live by accident.
-- is_listed works as it does everywhere (027): unticked, the post
-- is left out of "newest" but its page works and it can be pinned.
-- The body is content_blocks with owner_kind 'blog_post', slot
-- 'body'. Authors are people (blog_post_authors), or a guest named
-- on the post itself, or both. tags is a comma-separated list, eg.
-- 'Reflection, Event recap'; it is only displayed, never joined on.
--
-- content_blocks gains 'blog_post' as an owner. A CHECK can't be
-- altered in place, so the table is rebuilt; the *_cleanup triggers
-- on other tables name it, hence legacy_alter_table around the
-- rename. Its own index and owner trigger are recreated below.
--
-- featured_cards gains 'community_page' as an owner, the same way.
-- Nothing names it but its own triggers, recreated below.
--
-- community_page is a singleton like front_page: one row, made
-- here, which the admin edits and can't delete.
--
-- PRAGMA user_version; -- reads 30 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE blog_posts (
id TEXT PRIMARY KEY, -- slug: 'finding-unity-at-camp'
title TEXT NOT NULL,
excerpt TEXT, -- the card's text; else the body's start
cover_image TEXT, -- '/uploads/…', a filename, or a URL
published_on TEXT, -- 'YYYY-MM-DD'; newest first
tags TEXT, -- 'Reflection, Event recap'
guest_author TEXT, -- someone with no people row
guest_photo TEXT,
is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX blog_posts_newest_idx ON blog_posts (is_published, is_listed, published_on DESC);
CREATE TABLE blog_post_authors (
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (post_id, person_id)
) STRICT;
CREATE INDEX blog_post_authors_person_idx ON blog_post_authors (person_id);
CREATE TABLE community_page (
id TEXT PRIMARY KEY CHECK (id = 'community'),
blog_title TEXT, -- null → 'Community Blog'
blog_blurb TEXT,
internal_title TEXT, -- null → 'From NGU'
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT, -- null → 'From our community'
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT, -- the Substack home, for its button
external_label TEXT, -- null → 'Read more on Substack'
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO community_page (id) VALUES ('community');
CREATE TABLE community_page_pinned_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
UNIQUE (page_id, post_id)
) STRICT;
CREATE TABLE community_page_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, -- 'https://ngu.substack.com/feed'
label TEXT -- shown on its items; else the feed's own title
) STRICT;
-- ── content_blocks: add 'blog_post' ───────────────────────────
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider')),
text TEXT,
media TEXT,
href TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── featured_cards: add 'community_page' ──────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT,
title TEXT,
blurb TEXT,
image TEXT,
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image
FROM featured_cards;
PRAGMA legacy_alter_table = ON;
DROP TABLE featured_cards;
ALTER TABLE featured_cards_new RENAME TO featured_cards;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER blog_posts_cleanup
AFTER DELETE ON blog_posts
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'blog_post' AND owner_id = old.id;
END;
CREATE TRIGGER blog_posts_touch
AFTER UPDATE ON blog_posts
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE blog_posts SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER community_page_touch
AFTER UPDATE ON community_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE community_page SET updated_at = datetime('now') WHERE id = new.id;
END;

198
server/src/routes/blog.js Normal file
View file

@ -0,0 +1,198 @@
/* ═══════════════════════════════════════════════════════════════
BLOG ROUTES: read-only, mounted under /api
GET /blog/:id one published post, its body and authors
GET /community-blog the Community page's blog section
A post is public once published. Unlisted (is_listed = 0) keeps
its page but leaves it out of the section's "newest", though it
can still be pinned there: pinning is attaching it by hand.
The section has two halves, each pinned first and then newest,
up to its slot count (pinned posts always show, even past it):
internal blog_posts
external featured cards owned by the community page, then
items from its RSS/Atom feeds (feeds.js), skipping
any URL a pinned card already shows. Shaped as
featured cards, so FeaturedCards.tsx draws both.
Authors are published people, in order, and/or the post's guest
name. An author who is unpublished is left off rather than
named, the same as on every roster.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { asBool, loadBlocks, loadFeaturedCards, paragraphs } from "../shape.js";
import { readFeeds } from "../feeds.js";
const blog = new Hono();
const CACHE = "public, max-age=60, stale-while-revalidate=300";
const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE });
const marks = (n) => Array(n).fill("?").join(",");
const PAGE_ID = "community";
const splitTags = (tags) =>
(tags ?? "")
.split(",")
.map((tag) => tag.trim())
.filter(Boolean);
/* Published authors for a batch of posts, keyed by post id. */
function loadAuthors(db, ids) {
const byPost = new Map();
if (ids.length === 0) return byPost;
const rows = db
.prepare(
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id IN (${marks(ids.length)})
ORDER BY a.post_id, a.sort_order`,
)
.all(...ids);
for (const row of rows) {
const list = byPost.get(row.post_id) ?? [];
list.push({
id: row.id,
name: row.display_name,
pronouns: row.pronouns,
tagline: row.tagline,
photo: row.photo,
});
byPost.set(row.post_id, list);
}
return byPost;
}
function shapeSummary(row, authors, body) {
return {
id: row.id,
title: row.title,
// The card's text: the excerpt, else the body's first paragraph.
excerpt: row.excerpt || paragraphs(body)[0] || null,
cover_image: row.cover_image,
published_on: row.published_on,
tags: splitTags(row.tags),
authors: [
...authors.map((a) => ({ id: a.id, name: a.name })),
...(row.guest_author ? [{ id: null, name: row.guest_author }] : []),
],
};
}
/* ── One post ──────────────────────────────────────────────── */
blog.get("/blog/:id", (c) => {
const db = c.get("db");
const id = c.req.param("id");
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
if (!row) return c.json({ error: "No such post" }, 404);
const authors = loadAuthors(db, [id]).get(id) ?? [];
const body = loadBlocks(db, "blog_post", [id], "body").get(id) ?? [];
return json(c, {
post: {
id: row.id,
title: row.title,
excerpt: row.excerpt,
cover_image: row.cover_image,
published_on: row.published_on,
tags: splitTags(row.tags),
authors,
guest: row.guest_author ? { name: row.guest_author, photo: row.guest_photo } : null,
blocks: body,
is_listed: asBool(row.is_listed),
},
});
});
/* ── The Community page's section ──────────────────────────── */
blog.get("/community-blog", async (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM community_page WHERE id = ?`).get(PAGE_ID);
if (!page) return c.json({ error: "The community page hasn't been set up." }, 500);
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM community_page_pinned_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.page_id = ?
ORDER BY pp.sort_order`,
)
.all(PAGE_ID);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const ids = posts.map((row) => row.id);
const authors = loadAuthors(db, ids);
const bodies = loadBlocks(db, "blog_post", ids, "body");
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
const feedRows = db
.prepare(`SELECT url, label FROM community_page_feeds WHERE page_id = ? ORDER BY sort_order`)
.all(PAGE_ID);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return json(c, {
community_blog: {
title: page.blog_title,
blurb: page.blog_blurb,
internal: {
title: page.internal_title,
posts: posts.map((row) =>
shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []),
),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
},
});
});
export default blog;

View file

@ -18,6 +18,7 @@
teams published, and so is the organization
awards published
people published
blog_posts published
and each leaves out unlisted records (is_listed = 0): the QR page
is public, and listing them here would undo the point of them.
@ -70,6 +71,12 @@ directory.get("/directory", (c) => {
WHERE is_published = 1 AND is_listed = 1
ORDER BY COALESCE(sort_name, display_name)`,
),
blog_posts: all(
`SELECT id, title AS name
FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
ORDER BY published_on IS NULL, published_on DESC, title`,
),
},
},
200,