Files
jarv.is/lib/server/views.ts
jake d3b2d07de7 refactor: use "use cache: remote" for request-time reads and updateTag/refresh for mutations
- Replace `"use cache"` with `"use cache: remote"` on functions that run inside dynamic holes (`getContributions`, `getRepos`, `getPostStats`, `getCachedComments`) so entries are shared across server instances
- Switch comment and view server actions from `revalidatePath`/`revalidateTag` to `updateTag` + `refresh` for read-your-writes invalidation
- Extract a `commentsTag(pageSlug)` helper so each page's comment cache is expired independently instead of blowing the whole "comments" tag
- Refactor `getComments` to delegate to a cached inner function that throws on failure (so errors are never cached); `getCommentCount` now reuses that cache entry instead of issuing a separate COUNT query
- Drop `lib/data/views.ts` (`getAllViewCounts`) — the `/api/hits` route now calls `getPostStats()` instead
- Remove `revalidateTag("views")` from `incrementViews`; view counts in `getPostStats` are allowed to lag by a cache TTL
- Remove the `Suspense`/`Skeleton` wrapper on the projects page since `getContributions` is now a remote-cached call
2026-10-03 09:50:06 -04:00

35 lines
1022 B
TypeScript

"use server";
import { sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { page } from "@/lib/db/schema";
import { getPostByPageSlug } from "@/lib/posts";
/**
* Increments the view count for a given slug (upserts if doesn't exist)
*/
export const incrementViews = async (slug: string): Promise<number> => {
// this is a public endpoint: only count views for posts that actually exist
if (typeof slug !== "string" || !getPostByPageSlug(slug)) {
throw new Error("Invalid slug");
}
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 });
return result.views;
} catch (error) {
console.error("[server/views] error incrementing views:", error);
throw new Error("Failed to increment views", { cause: error });
}
};