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

+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;