saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
_middleware.js
2.4 KB · 52 lines
1// fills [data-social] with likes and comments from d1. if anything fails the2// page keeps its fallback text. runs on the paths in /_routes.json.3// /, /blog/ and /posts/ get my bluesky posts instead (../posts.js)45import { isLikeable, voterId, renderSocial } from "../lib.js";6import { POST_PAGES, withPosts } from "../posts.js";78export async function onRequest(context) {9 const { request, env } = context;10 const { pathname } = new URL(request.url);11 if (POST_PAGES.has(pathname) && (request.method === "GET" || request.method === "HEAD")) return withPosts(context);12 if (!isLikeable(pathname)) return context.next();1314 // the file never changes, so a 304 would show stale counts15 const fresh = new Request(request);16 fresh.headers.delete("If-None-Match");17 fresh.headers.delete("If-Modified-Since");18 const response = await context.next(fresh);19 if (!(response.headers.get("content-type") || "").includes("text/html")) return response;2021 let voter;22 try {23 voter = await voterId(env.SOCIAL_SECRET, request);24 } catch {25 return response;26 }2728 const page = new HTMLRewriter()29 .on("[data-social]", {30 async element(el) {31 // /now/ shows the current edition's, e.g. data-social="/now/sep-2026/"32 const key = el.getAttribute("data-social") || pathname;33 if (!isLikeable(key)) return;34 try {35 const [count, liked, comments] = await env.DB.batch([36 env.DB.prepare("SELECT count FROM Likes WHERE page = ?").bind(key),37 env.DB.prepare("SELECT 1 FROM LikeVoters WHERE page = ? AND voter = ?").bind(key, voter),38 env.DB.prepare("SELECT id, parent, name, body, is_author, created_at FROM Comments WHERE page = ? AND approved = 1 ORDER BY created_at").bind(key),39 ]);40 const likes = { count: Number(count.results[0]?.count ?? 0), liked: liked.results.length > 0 };41 el.setInnerContent(renderSocial(key, likes, comments.results), { html: true });42 } catch {}43 },44 })45 .transform(response);4647 // per visitor, so no shared or back-button copies48 const out = new Response(page.body, page);49 out.headers.set("Cache-Control", "private, no-cache");50 out.headers.delete("ETag");51 return out;52}