~james/core

core/web/src/lib/blog.ts -rw-r--r-- 1.2 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { fetchJson } from "#lib/fetchJson.ts";
import type { Fetch } from "#lib/fetch.ts";

const BLOG_URLS = ["https://tangled.org/blog", "https://next-dev.tangled.org/blog"];
const BLOG_ORIGINS = new Set(BLOG_URLS.map((url) => new URL(url).origin));
const FEED_TTL = 5 * 60_000;

export interface BlogFeedItem {
	url: string;
	title: string;
	summary?: string;
	image?: string;
	date_published: string;
	tags?: string[];
	authors?: { name: string; url?: string }[];
}

let cached: { expires: number; items: BlogFeedItem[] } | undefined;

export const loadBlogFeed = async (
	fetch: Fetch,
	timeout = 2500
): Promise<BlogFeedItem[] | null> => {
	if (cached && cached.expires > Date.now()) return cached.items;
	const feeds = BLOG_URLS.map((blogUrl) =>
		fetchJson<{ items?: BlogFeedItem[] }>(fetch, `${blogUrl}/feed.json`, timeout)
	);
	for (const pending of feeds) {
		const feed = await pending;
		if (!Array.isArray(feed?.items)) continue;
		const items = feed.items.flatMap((item) => {
			const url = URL.parse(item.url);
			return url && BLOG_ORIGINS.has(url.origin) ? [{ ...item, url: url.href }] : [];
		});
		cached = { expires: Date.now() + FEED_TTL, items };
		return items;
	}
	return null;
};