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

+1 -1
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { getAllViewCounts } from "@/lib/server/views";
import { getAllViewCounts } from "@/lib/data/views";
export const GET = async (): Promise<
NextResponse<{
+3 -1
View File
@@ -154,7 +154,9 @@ const Page = async ({ params }: PageProps<"/notes/[slug]">) => {
className="flex flex-nowrap items-center gap-1.5 whitespace-nowrap text-inherit hover:no-underline"
>
<IconMessages className="inline size-3.5 shrink-0" aria-hidden="true" />
<CommentCount slug={`${POSTS_DIR}/${post.slug}`} />
<Suspense fallback={<span className="motion-safe:animate-pulse">0</span>}>
<CommentCount slug={`${POSTS_DIR}/${post.slug}`} />
</Suspense>
</Link>
<div className="flex min-w-14 flex-nowrap items-center gap-1.5 whitespace-nowrap">
+6 -6
View File
@@ -1,9 +1,9 @@
import Link from "next/link";
import { ViewTransition } from "react";
import { Suspense, ViewTransition } from "react";
import { PageTitle } from "@/components/layout/page-title";
import { DirectionalTransition } from "@/components/page-transition";
import { PostStats, PostStatsProvider } from "@/components/post-stats";
import { PostStats, PostStatsSkeleton } from "@/components/post-stats";
import authorConfig from "@/lib/config/author";
import { createMetadata } from "@/lib/metadata";
import { type FrontMatter, getFrontMatter, POSTS_DIR } from "@/lib/posts";
@@ -79,7 +79,9 @@ const PostsList = () => {
/>
</ViewTransition>
<PostStats slug={`${POSTS_DIR}/${slug}`} />
<Suspense fallback={<PostStatsSkeleton />}>
<PostStats slug={`${POSTS_DIR}/${slug}`} />
</Suspense>
</div>
</li>
))}
@@ -95,9 +97,7 @@ const PostsList = () => {
const Page = () => (
<DirectionalTransition>
<PageTitle canonical="/notes">Notes</PageTitle>
<PostStatsProvider>
<PostsList />
</PostStatsProvider>
<PostsList />
</DirectionalTransition>
);
+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 };
+58
View File
@@ -0,0 +1,58 @@
import "server-only";
import { desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import * as schema from "@/lib/db/schema";
export type CommentWithUser = typeof schema.comment.$inferSelect & {
user: Pick<typeof schema.user.$inferSelect, "id" | "name" | "image">;
};
/**
* Retrieves all comments for a given slug, newest first, with each author's public profile fields
*/
export const getComments = async (pageSlug: string): Promise<CommentWithUser[]> => {
try {
// Fetch all comments for the page with user details
const commentsWithUsers = await db
.select()
.from(schema.comment)
.innerJoin(schema.user, eq(schema.comment.userId, schema.user.id))
.where(eq(schema.comment.pageSlug, pageSlug))
.orderBy(desc(schema.comment.createdAt));
return commentsWithUsers.map(({ comment, user }) =>
Object.assign(comment, {
user: {
// we're namely worried about keeping the user's email private here, but nothing sensitive is stored in the db
id: user.id,
name: user.name,
image: user.image,
},
}),
);
} catch (error) {
console.error("[data/comments] error fetching comments:", error);
// Return empty array instead of throwing during prerendering
return [];
}
};
/**
* Retrieves the number of comments for a given slug (uncached -- call from inside a <Suspense> boundary)
*/
export const getCommentCount = async (slug: string): Promise<number> => {
try {
const result = await db
.select({
count: sql<number>`cast(count(${schema.comment.id}) as int)`,
})
.from(schema.comment)
.where(eq(schema.comment.pageSlug, slug));
return result[0]?.count ?? 0;
} catch (error) {
console.error("[data/comments] error fetching comment count:", error);
return 0;
}
};
+42
View File
@@ -0,0 +1,42 @@
import "server-only";
import { sql } from "drizzle-orm";
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/lib/db";
import { comment, page } from "@/lib/db/schema";
export type PostStatsData = {
views: Record<string, number>;
comments: Record<string, number>;
};
/**
* View and comment counts for ALL pages, keyed by slug (e.g. "notes/dark-mode").
* Cached briefly; invalidated by `revalidateTag("views")` / `revalidateTag("comments")`.
*/
export const getPostStats = async (): Promise<PostStatsData> => {
"use cache";
cacheLife("minutes");
cacheTag("views", "comments");
try {
const [pageRows, commentRows] = await Promise.all([
db.select({ slug: page.slug, views: page.views }).from(page),
db
.select({
pageSlug: comment.pageSlug,
count: sql<number>`cast(count(${comment.id}) as int)`,
})
.from(comment)
.groupBy(comment.pageSlug),
]);
return {
views: Object.fromEntries(pageRows.map((row) => [row.slug, row.views])),
comments: Object.fromEntries(commentRows.map((row) => [row.pageSlug, row.count])),
};
} catch (error) {
console.error("[data/stats] error fetching post stats:", error);
return { views: {}, comments: {} };
}
};
+22
View File
@@ -0,0 +1,22 @@
import "server-only";
import { db } from "@/lib/db";
import { page } from "@/lib/db/schema";
/**
* Retrieves the numbers of views for ALL slugs (uncached)
*/
export const getAllViewCounts = async (): Promise<Record<string, number>> => {
try {
const pages = await db.select().from(page);
return pages.reduce(
(acc, p) => {
acc[p.slug] = p.views;
return acc;
},
{} as Record<string, number>,
);
} catch (error) {
console.error("[data/views] fatal error:", error);
return {};
}
};
+6 -78
View File
@@ -1,7 +1,7 @@
"use server";
import { desc, eq, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { eq } from "drizzle-orm";
import { revalidatePath, revalidateTag } from "next/cache";
import { headers } from "next/headers";
import { z } from "zod";
@@ -19,80 +19,6 @@ const createCommentSchema = z.object({
parentId: commentIdSchema.optional(),
});
export type CommentWithUser = typeof schema.comment.$inferSelect & {
user: Pick<typeof schema.user.$inferSelect, "id" | "name" | "image">;
};
export const getComments = async (pageSlug: string): Promise<CommentWithUser[]> => {
try {
// Fetch all comments for the page with user details
const commentsWithUsers = await db
.select()
.from(schema.comment)
.innerJoin(schema.user, eq(schema.comment.userId, schema.user.id))
.where(eq(schema.comment.pageSlug, pageSlug))
.orderBy(desc(schema.comment.createdAt));
return commentsWithUsers.map(({ comment, user }) =>
Object.assign(comment, {
user: {
// we're namely worried about keeping the user's email private here, but nothing sensitive is stored in the db
id: user.id,
name: user.name,
image: user.image,
},
}),
);
} catch (error) {
console.error("[server/comments] error fetching comments:", error);
// Return empty array instead of throwing during prerendering
return [];
}
};
/**
* Retrieves the number of comments for a given slug
*/
export const getCommentCount = async (slug: string): Promise<number> => {
try {
const result = await db
.select({
count: sql<number>`cast(count(${schema.comment.id}) as int)`,
})
.from(schema.comment)
.where(eq(schema.comment.pageSlug, slug));
return result[0]?.count ?? 0;
} catch (error) {
console.error("[server/comments] error fetching comment count:", error);
return 0;
}
};
/**
* Retrieves the numbers of comments for ALL slugs
*/
export const getAllCommentCounts = async (): Promise<Record<string, number>> => {
try {
const rows = await db
.select({
pageSlug: schema.comment.pageSlug,
count: sql<number>`cast(count(${schema.comment.id}) as int)`,
})
.from(schema.comment)
.groupBy(schema.comment.pageSlug);
const map: Record<string, number> = {};
for (const row of rows) {
map[row.pageSlug] = row.count ?? 0;
}
return map;
} catch (error) {
console.error("[server/comments] error fetching comment counts:", error);
return {};
}
};
export const createComment = async (data: {
content: string;
pageSlug: string;
@@ -140,8 +66,9 @@ export const createComment = async (data: {
userId: session.user.id,
});
// Revalidate page
// Revalidate page and the cached comment counts
revalidatePath(`/${pageSlug}`);
revalidateTag("comments", "max");
} catch (error) {
console.error("[server/comments] error creating comment:", error);
throw new Error("Failed to create comment", { cause: error });
@@ -236,8 +163,9 @@ export const deleteComment = async (commentId: string) => {
// Delete the comment
await db.delete(schema.comment).where(eq(schema.comment.id, commentId));
// Revalidate page
// Revalidate page and the cached comment counts
revalidatePath(`/${comment.pageSlug}`);
revalidateTag("comments", "max");
} catch (error) {
console.error("[server/comments] error deleting comment:", error);
throw new Error("Failed to delete comment", { cause: error });
+2 -34
View File
@@ -1,44 +1,12 @@
"use server";
import { eq, sql } from "drizzle-orm";
import { sql } from "drizzle-orm";
import { revalidateTag } from "next/cache";
import { db } from "@/lib/db";
import { page } from "@/lib/db/schema";
import { getPostByPageSlug } from "@/lib/posts";
/**
* Retrieves the number of views for a given slug, or 0 if the slug does not exist or on error
*/
export const getViewCount = async (slug: string): Promise<number> => {
try {
const pages = await db.select().from(page).where(eq(page.slug, slug)).limit(1);
return pages[0]?.views ?? 0;
} catch (error) {
console.error("[server/views] fatal error:", error);
return 0;
}
};
/**
* Retrieves the numbers of views for ALL slugs
*/
export const getAllViewCounts = async (): Promise<Record<string, number>> => {
try {
const pages = await db.select().from(page);
return pages.reduce(
(acc, p) => {
acc[p.slug] = p.views;
return acc;
},
{} as Record<string, number>,
);
} catch (error) {
console.error("[server/views] fatal error:", error);
return {};
}
};
/**
* Increments the view count for a given slug (upserts if doesn't exist)
*/
@@ -59,7 +27,7 @@ export const incrementViews = async (slug: string): Promise<number> => {
})
.returning({ views: page.views });
// Invalidate the views cache so getViewCount returns fresh data
// Mark the cached post stats (lib/data/stats.ts) stale so lists pick up the new count
revalidateTag("views", "max");
return result.views;