refactor: move read queries into server-only lib/data and render post stats on the server

Reads no longer live in "use server" files (which made them public
endpoints). /notes stats come from one cached query pair rendered on the
server; the post page comment count streams in as a dynamic hole.
revalidateTag("views"/"comments") now invalidates the cached stats.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
jakeandClaude Sonnet 5.5 committed 2026-10-03 08:40:14 -04:00
1 parent bd18c6d553
commit 6d255ce822
14 files changed
+164 -209

No files matched your search

+7 -33
View File
@@ -1,40 +1,14 @@
"use client";
import NumberFlow from "@number-flow/react";
import { useEffect, useState } from "react";
import { connection } from "next/server";
import { getCommentCount } from "@/lib/server/comments";
import { getCommentCount } from "@/lib/data/comments";
const CommentCount = ({ slug }: { slug: string }) => {
const [count, setCount] = useState<number | null>(null);
const [error, setError] = useState(false);
const CommentCount = async ({ slug }: { slug: string }) => {
// render per-request (as a dynamic hole) so the post's static shell keeps its long cache lifetime
await connection();
const count = await getCommentCount(slug);
useEffect(() => {
getCommentCount(slug)
.then((result: number) => {
setCount(result);
})
.catch((err: unknown) => {
console.error("[comment-count] error:", err);
setError(true);
});
}, [slug]);
if (error) {
return <span title="Error getting comments">?</span>;
}
if (count === null) {
return <span className="motion-safe:animate-pulse">0</span>;
}
return (
<NumberFlow
className={count === null ? "motion-safe:animate-pulse" : undefined}
locales={process.env.NEXT_PUBLIC_SITE_LOCALE}
value={count}
/>
);
return <NumberFlow locales={process.env.NEXT_PUBLIC_SITE_LOCALE} value={count} />;
};
export { CommentCount };
+2 -1
View File
@@ -23,7 +23,8 @@ import {
import { Spinner } from "@/components/ui/spinner";
import { toast } from "@/components/ui/toast";
import { useSession } from "@/lib/auth-client";
import { type CommentWithUser, deleteComment } from "@/lib/server/comments";
import type { CommentWithUser } from "@/lib/data/comments";
import { deleteComment } from "@/lib/server/comments";
import { EditCommentForm, ReplyForm } from "./comment-form";
+1 -1
View File
@@ -2,9 +2,9 @@ import Link from "next/link";
import Markdown from "react-markdown";
import { RelativeTime } from "@/components/relative-time";
import type { CommentWithUser } from "@/lib/data/comments";
import { rehypeExternalLinks } from "@/lib/rehype";
import { remarkGfm, remarkSmartypants } from "@/lib/remark";
import type { CommentWithUser } from "@/lib/server/comments";
import { cn } from "@/lib/utils";
import { CommentActions } from "./comment-actions";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { CommentWithUser } from "@/lib/server/comments";
import type { CommentWithUser } from "@/lib/data/comments";
import { cn } from "@/lib/utils";
import { CommentSingle } from "./comment-single";
+1 -1
View File
@@ -1,7 +1,7 @@
import { headers } from "next/headers";
import { auth } from "@/lib/auth";
import { type CommentWithUser, getComments } from "@/lib/server/comments";
import { type CommentWithUser, getComments } from "@/lib/data/comments";
import { NewCommentForm } from "./comment-form";
import { CommentThread } from "./comment-thread";
+12 -52
View File
@@ -1,68 +1,28 @@
"use client";
import { IconEye, IconMessages } from "@tabler/icons-react";
import Link from "next/link";
import { createContext, type ReactNode, useContext, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { getAllCommentCounts } from "@/lib/server/comments";
import { getAllViewCounts } from "@/lib/server/views";
import { getPostStats } from "@/lib/data/stats";
const numberFormatter = new Intl.NumberFormat(process.env.NEXT_PUBLIC_SITE_LOCALE);
type Stats = {
views: Record<string, number>;
comments: Record<string, number>;
loaded: boolean;
};
const StatsContext = createContext<Stats>({
views: {},
comments: {},
loaded: false,
});
/**
* Provider that fetches ALL post stats in a single batch (2 requests total).
* Wrap this around any component tree that contains PostStats components.
* Placeholder shown while the stats for a post are loading.
*/
export const PostStatsProvider = ({ children }: { children: ReactNode }) => {
const [stats, setStats] = useState<Stats>({
views: {},
comments: {},
loaded: false,
});
useEffect(() => {
Promise.all([getAllViewCounts(), getAllCommentCounts()])
.then(([views, comments]) => {
setStats({ views, comments, loaded: true });
})
.catch((err) => {
console.error("[post-stats] error fetching stats:", err);
setStats({ views: {}, comments: {}, loaded: true });
});
}, []);
return <StatsContext.Provider value={stats}>{children}</StatsContext.Provider>;
};
const PostStatsSkeleton = () => (
<>
<Skeleton className="inline-block h-5 w-16 translate-y-[-2px] rounded-4xl border border-transparent align-middle" />
<Skeleton className="inline-block h-5 w-12 translate-y-[-2px] rounded-4xl border border-transparent align-middle" />
</>
);
/**
* Displays view/comment badges for a single post.
* Must be used within a PostStatsProvider.
* Every instance shares one cached getPostStats() result.
*/
const PostStats = ({ slug }: { slug: string }) => {
const { views, comments, loaded } = useContext(StatsContext);
if (!loaded) {
return (
<>
<Skeleton className="inline-block h-5 w-16 translate-y-[-2px] rounded-4xl border border-transparent align-middle" />
<Skeleton className="inline-block h-5 w-12 translate-y-[-2px] rounded-4xl border border-transparent align-middle" />
</>
);
}
const PostStats = async ({ slug }: { slug: string }) => {
const { views, comments } = await getPostStats();
const viewCount = views[slug] ?? 0;
const commentCount = comments[slug] ?? 0;
@@ -98,4 +58,4 @@ const PostStats = ({ slug }: { slug: string }) => {
);
};
export { PostStats };
export { PostStats, PostStatsSkeleton };