1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2026-06-05 19:15:30 -04:00

chore: Next.js 15 → 16 (#2503)

This commit is contained in:
2025-11-22 17:11:42 -05:00
committed by GitHub
parent 19960ca2b0
commit 8a09aa918c
27 changed files with 2457 additions and 2304 deletions
+58 -58
View File
@@ -1,5 +1,4 @@
import { env } from "@/lib/env";
import { cache } from "react";
import path from "path";
import fs from "fs/promises";
import glob from "fast-glob";
@@ -31,7 +30,9 @@ export type FrontMatter = {
export const POSTS_DIR = "notes" as const;
/** Use filesystem to get a simple list of all post slugs */
export const getSlugs = cache(async (): Promise<string[]> => {
export const getSlugs = async (): Promise<string[]> => {
"use cache";
// list all .mdx files in POSTS_DIR
const mdxFiles = await glob("*/index.mdx", {
cwd: path.join(process.cwd(), POSTS_DIR),
@@ -42,7 +43,7 @@ export const getSlugs = cache(async (): Promise<string[]> => {
const slugs = mdxFiles.map((fileName) => fileName.replace(/\/index\.mdx$/, ""));
return slugs;
});
};
export const getFrontMatter: {
/**
@@ -53,67 +54,66 @@ export const getFrontMatter: {
* Parses and returns the front matter of a given slug, or undefined if the slug does not exist
*/
(slug: string): Promise<FrontMatter | undefined>;
} = cache(
async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slug?: any
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
Promise<any> => {
if (typeof slug === "string") {
try {
const { frontmatter } = await import(`../${POSTS_DIR}/${slug}/index.mdx`);
} = (async (slug?: string) => {
"use cache";
// process markdown title to html...
const htmlTitle = await unified()
.use(remarkParse)
.use(remarkSmartypants)
.use(remarkRehype)
.use(rehypeSanitize, {
// allow *very* limited markdown to be used in post titles
tagNames: ["code", "em", "strong"],
})
.use(rehypeStringify)
.process(frontmatter.title)
.then((result) => result.toString().trim());
if (typeof slug === "string") {
try {
const { frontmatter } = await import(`../${POSTS_DIR}/${slug}/index.mdx`);
// ...and then (sketchily) remove said html for a plaintext version:
// https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
const title = decode(htmlTitle.replace(/<[^>]*>/g, ""));
// process markdown title to html...
const htmlTitle = await unified()
.use(remarkParse)
.use(remarkSmartypants)
.use(remarkRehype)
.use(rehypeSanitize, {
// allow *very* limited markdown to be used in post titles
tagNames: ["code", "em", "strong"],
})
.use(rehypeStringify)
.process(frontmatter.title)
.then((result) => result.toString().trim());
return {
...(frontmatter as Partial<FrontMatter>),
// plain title without html or markdown syntax:
title,
// stylized title with limited html tags:
htmlTitle,
slug,
// validate/normalize the date string provided from front matter
date: new Date(frontmatter.date).toISOString(),
permalink: `${env.NEXT_PUBLIC_BASE_URL}/${POSTS_DIR}/${slug}`,
} as FrontMatter;
} catch (error) {
console.error(`Failed to load front matter for post with slug "${slug}":`, error);
return undefined;
}
// ...and then (sketchily) remove said html for a plaintext version:
// https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
const title = decode(htmlTitle.replace(/<[^>]*>/g, ""));
return {
...(frontmatter as Partial<FrontMatter>),
// plain title without html or markdown syntax:
title,
// stylized title with limited html tags:
htmlTitle,
slug,
// validate/normalize the date string provided from front matter
date: new Date(frontmatter.date).toISOString(),
permalink: `${env.NEXT_PUBLIC_BASE_URL}/${POSTS_DIR}/${slug}`,
} as FrontMatter;
} catch (error) {
console.error(`Failed to load front matter for post with slug "${slug}":`, error);
return undefined;
}
if (!slug) {
// concurrently fetch the front matter of each post
const slugs = await getSlugs();
const posts = await Promise.all(slugs.map(getFrontMatter));
// sort the results reverse chronologically and return
return posts.sort(
(post1, post2) => new Date(post2!.date).getTime() - new Date(post1!.date).getTime()
) as FrontMatter[];
}
throw new Error("getFrontMatter() called with invalid argument.");
}
);
if (!slug) {
// concurrently fetch the front matter of each post
const slugs = await getSlugs();
const allPosts = await Promise.all(slugs.map(getFrontMatter));
// filter out any undefined entries from failed imports
const posts = allPosts.filter((p): p is FrontMatter => !!p);
// sort the results reverse chronologically and return
return posts.sort((post1, post2) => new Date(post2.date).getTime() - new Date(post1.date).getTime());
}
throw new Error("getFrontMatter() called with invalid argument.");
}) as typeof getFrontMatter;
/** Returns the content of a post with very limited processing to include in RSS feeds */
export const getContent = cache(async (slug: string): Promise<string | undefined> => {
export const getContent = async (slug: string): Promise<string | undefined> => {
"use cache";
try {
const content = await unified()
.use(remarkParse)
@@ -153,4 +153,4 @@ export const getContent = cache(async (slug: string): Promise<string | undefined
console.error(`Failed to load/parse content for post with slug "${slug}":`, error);
return undefined;
}
});
};
+22 -6
View File
@@ -1,7 +1,7 @@
"use server";
import { headers } from "next/headers";
import { revalidatePath } from "next/cache";
import { revalidatePath, revalidateTag, cacheTag } from "next/cache";
import { eq, desc, inArray, sql } from "drizzle-orm";
import { checkBotId } from "botid/server";
import { db } from "@/lib/db";
@@ -13,6 +13,9 @@ 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
@@ -33,7 +36,8 @@ export const getComments = async (pageSlug: string): Promise<CommentWithUser[]>
}));
} catch (error) {
console.error("[server/comments] error fetching comments:", error);
throw new Error("Failed to fetch comments");
// Return empty array instead of throwing during prerendering
return [];
}
};
@@ -55,6 +59,9 @@ export const getCommentCounts: {
slug?: any
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
Promise<any> => {
"use cache";
cacheTag("comments");
try {
// return one page
if (typeof slug === "string") {
@@ -102,7 +109,10 @@ Promise<any> => {
return map;
} catch (error) {
console.error("[server/comments] error fetching comment counts:", error);
throw new Error("Failed to fetch comment counts");
// 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 {};
}
};
@@ -131,7 +141,9 @@ export const createComment = async (data: { content: string; pageSlug: string; p
userId: session.user.id,
});
// Revalidate the page to show the new comment
// Revalidate caches and paths
revalidateTag("comments", "max");
revalidateTag(`comments-${data.pageSlug}`, "max");
revalidatePath(`/${data.pageSlug}`);
// Also revalidate the notes listing to update comment count badges
revalidatePath("/notes");
@@ -183,7 +195,9 @@ export const updateComment = async (commentId: string, content: string) => {
})
.where(eq(schema.comment.id, commentId));
// Revalidate the page to show the updated comment
// Revalidate caches and paths
revalidateTag("comments", "max");
revalidateTag(`comments-${comment.pageSlug}`, "max");
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
@@ -230,7 +244,9 @@ export const deleteComment = async (commentId: string) => {
// Delete the comment
await db.delete(schema.comment).where(eq(schema.comment.id, commentId));
// Revalidate the page to update the comments list
// Revalidate caches and paths
revalidateTag("comments", "max");
revalidateTag(`comments-${comment.pageSlug}`, "max");
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
+29
View File
@@ -0,0 +1,29 @@
"use server";
import { sql } from "drizzle-orm";
import { revalidateTag } from "next/cache";
import { db } from "@/lib/db";
import { page } from "@/lib/db/schema";
export const incrementViews = async (slug: string): Promise<number> => {
try {
// Atomic upsert: insert new row with views=1, or increment existing row
const [result] = await db
.insert(page)
.values({ slug, views: 1 })
.onConflictDoUpdate({
target: page.slug,
set: { views: sql`${page.views} + 1` },
})
.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"
revalidateTag("views", "max");
return result.views;
} catch (error) {
console.error("[actions/views] error incrementing views:", error);
throw new Error("Failed to increment views");
}
};
+20 -44
View File
@@ -1,69 +1,42 @@
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 incrementViews = async (slug: string): Promise<number> => {
try {
// First, try to find the existing record
const existingPage = await db.select().from(page).where(eq(page.slug, slug)).limit(1);
if (existingPage.length === 0) {
// Create new record if it doesn't exist
await db.insert(page).values({ slug, views: 1 }).execute();
return 1; // New record starts with 1 hit
} else {
// Calculate new hit count
const newViewCount = existingPage[0].views + 1;
// Update existing record by incrementing hits
await db.update(page).set({ views: newViewCount }).where(eq(page.slug, slug)).execute();
return newViewCount;
}
} catch (error) {
console.error("[view-counter] fatal error:", error);
throw new Error("Failed to increment views");
}
};
export const getViewCounts: {
/**
* Retrieves the number of views for a given slug, or null if the slug does not exist
* Retrieves the number of views for a given slug, or 0 if the slug does not exist or on error
*/
(slug: string): Promise<number | null>;
(slug: string): Promise<number>;
/**
* Retrieves the numbers of views for an array of slugs
* Retrieves the numbers of views for an array of slugs, returning 0 for any that don't exist
*/
(slug: string[]): Promise<Record<string, number | null>>;
(slug: string[]): Promise<Record<string, number>>;
/**
* Retrieves the numbers of views 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> => {
} = (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;
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));
return pages.reduce(
(acc, page, index) => {
acc[slug[index]] = page.views;
return acc;
},
{} as Record<string, number | null>
);
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
@@ -77,6 +50,9 @@ Promise<any> => {
);
} catch (error) {
console.error("[server/views] fatal error:", error);
throw new Error("Failed to get views");
// 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;