mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2026-06-05 19:15:30 -04:00
fix: don't pre-render view and comment count components
- Introduced a new PostStats component to handle view and comment counts, replacing the previous async implementation with a client-side approach. - Updated CommentCount component to use client-side state management for fetching comment counts. - Removed unnecessary caching logic from view and comment fetching functions. - Simplified date formatting by moving it inline, enhancing performance and readability.
This commit is contained in:
-13
@@ -1,13 +0,0 @@
|
||||
import { env } from "@/lib/env";
|
||||
import { format, formatISO } from "date-fns";
|
||||
import { enUS } from "date-fns/locale";
|
||||
import { tz } from "@date-fns/tz";
|
||||
import { utc } from "@date-fns/utc";
|
||||
|
||||
export const formatDate = (date: string | number | Date, formatStr = "PPpp") => {
|
||||
return format(date, formatStr, { in: tz(env.NEXT_PUBLIC_SITE_TZ), locale: enUS });
|
||||
};
|
||||
|
||||
export const formatDateISO = (date: string | number | Date) => {
|
||||
return formatISO(date, { in: utc });
|
||||
};
|
||||
@@ -128,14 +128,6 @@ export const env = createEnv({
|
||||
* @see https://www.loc.gov/standards/iso639-2/php/code_list.php
|
||||
*/
|
||||
NEXT_PUBLIC_SITE_LOCALE: z.string().default("en-US"),
|
||||
|
||||
/**
|
||||
* Optional. Consistent timezone for the site. Doesn't really matter what it is, as long as it's the same everywhere
|
||||
* to avoid hydration complaints. Defaults to `America/New_York`.
|
||||
*
|
||||
* @see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List
|
||||
*/
|
||||
NEXT_PUBLIC_SITE_TZ: z.string().default("America/New_York"),
|
||||
},
|
||||
experimental__runtimeEnv: {
|
||||
NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL,
|
||||
@@ -144,7 +136,6 @@ export const env = createEnv({
|
||||
NEXT_PUBLIC_GITHUB_USERNAME: process.env.NEXT_PUBLIC_GITHUB_USERNAME,
|
||||
NEXT_PUBLIC_ONION_DOMAIN: process.env.NEXT_PUBLIC_ONION_DOMAIN,
|
||||
NEXT_PUBLIC_SITE_LOCALE: process.env.NEXT_PUBLIC_SITE_LOCALE,
|
||||
NEXT_PUBLIC_SITE_TZ: process.env.NEXT_PUBLIC_SITE_TZ,
|
||||
},
|
||||
emptyStringAsUndefined: true,
|
||||
skipValidation: !!process.env.SKIP_ENV_VALIDATION,
|
||||
|
||||
+49
-73
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import { revalidatePath, revalidateTag, cacheTag } from "next/cache";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { eq, desc, inArray, sql } from "drizzle-orm";
|
||||
import { checkBotId } from "botid/server";
|
||||
import { db } from "@/lib/db";
|
||||
@@ -13,9 +13,6 @@ export type CommentWithUser = typeof schema.comment.$inferSelect & {
|
||||
};
|
||||
|
||||
export const getComments = async (pageSlug: string): Promise<CommentWithUser[]> => {
|
||||
"use cache";
|
||||
cacheTag("comments", `comments-${pageSlug}`);
|
||||
|
||||
try {
|
||||
// Fetch all comments for the page with user details
|
||||
const commentsWithUsers = await db
|
||||
@@ -41,59 +38,55 @@ export const getComments = async (pageSlug: string): Promise<CommentWithUser[]>
|
||||
}
|
||||
};
|
||||
|
||||
export const getCommentCounts: {
|
||||
/**
|
||||
* Retrieves the number of comments for a given slug
|
||||
*/
|
||||
(slug: string): Promise<number>;
|
||||
/**
|
||||
* Retrieves the numbers of comments for an array of slugs
|
||||
*/
|
||||
(slug: string[]): Promise<Record<string, number>>;
|
||||
/**
|
||||
* Retrieves the numbers of comments for ALL slugs
|
||||
*/
|
||||
(): Promise<Record<string, number>>;
|
||||
} = async (
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
slug?: any
|
||||
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
Promise<any> => {
|
||||
"use cache";
|
||||
cacheTag("comments");
|
||||
|
||||
/**
|
||||
* Retrieves the number of comments for a given slug
|
||||
*/
|
||||
export const getCommentCount = async (slug: string): Promise<number> => {
|
||||
try {
|
||||
// return one page
|
||||
if (typeof slug === "string") {
|
||||
const result = await db
|
||||
.select({
|
||||
count: sql<number>`cast(count(${schema.comment.id}) as int)`,
|
||||
})
|
||||
.from(schema.comment)
|
||||
.where(eq(schema.comment.pageSlug, slug));
|
||||
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 Number(result[0]?.count ?? 0);
|
||||
return Number(result[0]?.count ?? 0);
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error fetching comment count:", error);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the numbers of comments for an array of slugs
|
||||
*/
|
||||
export const getCommentCountsForSlugs = async (slugs: string[]): 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)
|
||||
.where(inArray(schema.comment.pageSlug, slugs))
|
||||
.groupBy(schema.comment.pageSlug);
|
||||
|
||||
const map: Record<string, number> = Object.fromEntries(slugs.map((s) => [s, 0]));
|
||||
for (const row of rows) {
|
||||
map[row.pageSlug] = Number(row.count ?? 0);
|
||||
}
|
||||
return map;
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error fetching comment counts:", error);
|
||||
return Object.fromEntries(slugs.map((s) => [s, 0]));
|
||||
}
|
||||
};
|
||||
|
||||
// return multiple pages
|
||||
if (Array.isArray(slug)) {
|
||||
const rows = await db
|
||||
.select({
|
||||
pageSlug: schema.comment.pageSlug,
|
||||
count: sql<number>`cast(count(${schema.comment.id}) as int)`,
|
||||
})
|
||||
.from(schema.comment)
|
||||
.where(inArray(schema.comment.pageSlug, slug))
|
||||
.groupBy(schema.comment.pageSlug);
|
||||
|
||||
const map: Record<string, number> = Object.fromEntries(slug.map((s: string) => [s, 0]));
|
||||
for (const row of rows) {
|
||||
map[row.pageSlug] = Number(row.count ?? 0);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// return ALL pages
|
||||
/**
|
||||
* 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,
|
||||
@@ -109,9 +102,6 @@ Promise<any> => {
|
||||
return map;
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error fetching comment counts:", error);
|
||||
// Return sensible defaults instead of throwing during prerendering
|
||||
if (typeof slug === "string") return 0;
|
||||
if (Array.isArray(slug)) return Object.fromEntries(slug.map((s: string) => [s, 0]));
|
||||
return {};
|
||||
}
|
||||
};
|
||||
@@ -141,12 +131,8 @@ export const createComment = async (data: { content: string; pageSlug: string; p
|
||||
userId: session.user.id,
|
||||
});
|
||||
|
||||
// Revalidate caches and paths
|
||||
revalidateTag("comments", "max");
|
||||
revalidateTag(`comments-${data.pageSlug}`, "max");
|
||||
// Revalidate page
|
||||
revalidatePath(`/${data.pageSlug}`);
|
||||
// Also revalidate the notes listing to update comment count badges
|
||||
revalidatePath("/notes");
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error creating comment:", error);
|
||||
throw new Error("Failed to create comment");
|
||||
@@ -195,13 +181,8 @@ export const updateComment = async (commentId: string, content: string) => {
|
||||
})
|
||||
.where(eq(schema.comment.id, commentId));
|
||||
|
||||
// Revalidate caches and paths
|
||||
revalidateTag("comments", "max");
|
||||
revalidateTag(`comments-${comment.pageSlug}`, "max");
|
||||
// Revalidate page
|
||||
revalidatePath(`/${comment.pageSlug}`);
|
||||
// Also revalidate the notes listing to update comment count badges
|
||||
// TODO: make this more generic in case we want to add comments to non-note pages
|
||||
revalidatePath("/notes");
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error updating comment:", error);
|
||||
throw new Error("Failed to update comment");
|
||||
@@ -244,13 +225,8 @@ export const deleteComment = async (commentId: string) => {
|
||||
// Delete the comment
|
||||
await db.delete(schema.comment).where(eq(schema.comment.id, commentId));
|
||||
|
||||
// Revalidate caches and paths
|
||||
revalidateTag("comments", "max");
|
||||
revalidateTag(`comments-${comment.pageSlug}`, "max");
|
||||
// Revalidate page
|
||||
revalidatePath(`/${comment.pageSlug}`);
|
||||
// Also revalidate the notes listing to update comment count badges
|
||||
// TODO: make this more generic in case we want to add comments to non-note pages
|
||||
revalidatePath("/notes");
|
||||
} catch (error) {
|
||||
console.error("[server/comments] error deleting comment:", error);
|
||||
throw new Error("Failed to delete comment");
|
||||
|
||||
+55
-4
@@ -1,10 +1,62 @@
|
||||
"use server";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { eq, inArray, sql } from "drizzle-orm";
|
||||
import { revalidateTag } from "next/cache";
|
||||
import { db } from "@/lib/db";
|
||||
import { page } from "@/lib/db/schema";
|
||||
|
||||
/**
|
||||
* 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 an array of slugs, returning 0 for any that don't exist
|
||||
*/
|
||||
export const getViewCountsForSlugs = async (slugs: string[]): Promise<Record<string, number>> => {
|
||||
try {
|
||||
const pages = await db.select().from(page).where(inArray(page.slug, slugs));
|
||||
const viewMap: Record<string, number> = Object.fromEntries(slugs.map((s) => [s, 0]));
|
||||
for (const p of pages) {
|
||||
viewMap[p.slug] = p.views;
|
||||
}
|
||||
return viewMap;
|
||||
} catch (error) {
|
||||
console.error("[server/views] fatal error:", error);
|
||||
return Object.fromEntries(slugs.map((s) => [s, 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)
|
||||
*/
|
||||
export const incrementViews = async (slug: string): Promise<number> => {
|
||||
try {
|
||||
// Atomic upsert: insert new row with views=1, or increment existing row
|
||||
@@ -17,13 +69,12 @@ export const incrementViews = async (slug: string): Promise<number> => {
|
||||
})
|
||||
.returning({ views: page.views });
|
||||
|
||||
// Invalidate the views cache so getViewCounts returns fresh data
|
||||
// This is safe here because this entire file is marked "use server"
|
||||
// Invalidate the views cache so getViewCount returns fresh data
|
||||
revalidateTag("views", "max");
|
||||
|
||||
return result.views;
|
||||
} catch (error) {
|
||||
console.error("[actions/views] error incrementing views:", error);
|
||||
console.error("[server/views] error incrementing views:", error);
|
||||
throw new Error("Failed to increment views");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,3 +4,17 @@ import { twMerge } from "tailwind-merge";
|
||||
export const cn = (...inputs: ClassValue[]) => {
|
||||
return twMerge(clsx(inputs));
|
||||
};
|
||||
|
||||
/**
|
||||
* Recursively extracts plain text content from React nodes.
|
||||
* Replacement for the `react-to-text` package.
|
||||
*/
|
||||
export const getTextContent = (node: React.ReactNode): string => {
|
||||
if (node == null || typeof node === "boolean") return "";
|
||||
if (typeof node === "string" || typeof node === "number") return String(node);
|
||||
if (Array.isArray(node)) return node.map(getTextContent).join("");
|
||||
if (typeof node === "object" && "props" in node) {
|
||||
return getTextContent((node as React.ReactElement<{ children?: React.ReactNode }>).props.children);
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import "server-only";
|
||||
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { cacheTag } from "next/cache";
|
||||
import { db } from "@/lib/db";
|
||||
import { page } from "@/lib/db/schema";
|
||||
|
||||
export const getViewCounts: {
|
||||
/**
|
||||
* Retrieves the number of views for a given slug, or 0 if the slug does not exist or on error
|
||||
*/
|
||||
(slug: string): Promise<number>;
|
||||
/**
|
||||
* Retrieves the numbers of views for an array of slugs, returning 0 for any that don't exist
|
||||
*/
|
||||
(slug: string[]): Promise<Record<string, number>>;
|
||||
/**
|
||||
* Retrieves the numbers of views for ALL slugs
|
||||
*/
|
||||
(): Promise<Record<string, number>>;
|
||||
} = (async (slug?: string | string[]) => {
|
||||
"use cache";
|
||||
cacheTag("views");
|
||||
|
||||
try {
|
||||
// return one page
|
||||
if (typeof slug === "string") {
|
||||
const pages = await db.select().from(page).where(eq(page.slug, slug)).limit(1);
|
||||
return pages[0]?.views ?? 0; // Return 0 if no row found
|
||||
}
|
||||
|
||||
// return multiple pages
|
||||
if (Array.isArray(slug)) {
|
||||
const pages = await db.select().from(page).where(inArray(page.slug, slug));
|
||||
const viewMap: Record<string, number> = Object.fromEntries(slug.map((s) => [s, 0]));
|
||||
for (const p of pages) {
|
||||
viewMap[p.slug] = p.views;
|
||||
}
|
||||
return viewMap;
|
||||
}
|
||||
|
||||
// return ALL pages
|
||||
const pages = await db.select().from(page);
|
||||
return pages.reduce(
|
||||
(acc, page) => {
|
||||
acc[page.slug] = page.views;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, number>
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[server/views] fatal error:", error);
|
||||
// Return sensible defaults instead of throwing during prerendering
|
||||
if (typeof slug === "string") return 0;
|
||||
if (Array.isArray(slug)) return Object.fromEntries(slug.map((s) => [s, 0]));
|
||||
return {};
|
||||
}
|
||||
}) as typeof getViewCounts;
|
||||
Reference in New Issue
Block a user