mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-10-30 03:36:03 -04:00
display each post's view count in list
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { unstable_cache as cache } from "next/cache";
|
||||
import { kv } from "@vercel/kv";
|
||||
import { getViews as _getViews } from "@/lib/posts";
|
||||
import { POSTS_DIR } from "@/lib/config/constants";
|
||||
|
||||
// cache response from the db
|
||||
const getData = cache(
|
||||
async (): Promise<{
|
||||
const getViews = cache(_getViews, undefined, {
|
||||
revalidate: 300, // 5 minutes
|
||||
tags: ["hits"],
|
||||
});
|
||||
|
||||
export const GET = async (): Promise<
|
||||
NextResponse<{
|
||||
total: {
|
||||
hits: number;
|
||||
};
|
||||
@@ -12,42 +17,20 @@ const getData = cache(
|
||||
slug: string;
|
||||
hits: number;
|
||||
}>;
|
||||
}> => {
|
||||
// get all keys (aka slugs)
|
||||
const slugs = await kv.scan(0, {
|
||||
match: "hits:*",
|
||||
type: "string",
|
||||
// set an arbitrary yet generous upper limit, just in case...
|
||||
count: 99,
|
||||
});
|
||||
}>
|
||||
> => {
|
||||
// note: while hits have been renamed to views in most places, this API shouldn't change due to it being snapshotted
|
||||
const views = await getViews();
|
||||
|
||||
// get the value (number of hits) for each key (the slug of the page)
|
||||
const values = await kv.mget<string[]>(...slugs[1]);
|
||||
const total = {
|
||||
hits: Object.values(views).reduce((acc, curr) => acc + curr, 0),
|
||||
};
|
||||
const pages = Object.entries(views).map(([slug, hits]) => ({
|
||||
slug: `${POSTS_DIR}/${slug}`,
|
||||
hits,
|
||||
}));
|
||||
|
||||
// pair the slugs with their hit values
|
||||
const pages = slugs[1].map((slug, index) => ({
|
||||
slug: slug.split(":").pop() as string, // remove the "hits:" prefix
|
||||
hits: parseInt(values[index], 10),
|
||||
}));
|
||||
pages.sort((a, b) => b.hits - a.hits);
|
||||
|
||||
// sort descending by hits
|
||||
pages.sort((a, b) => b.hits - a.hits);
|
||||
|
||||
// calculate total hits
|
||||
const total = { hits: 0 };
|
||||
pages.forEach((page) => {
|
||||
// add these hits to running tally
|
||||
total.hits += page.hits;
|
||||
});
|
||||
|
||||
return { total, pages };
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
revalidate: 300, // 5 minutes
|
||||
tags: ["hits"],
|
||||
}
|
||||
);
|
||||
|
||||
export const GET = async (): Promise<NextResponse<Awaited<ReturnType<typeof getData>>>> =>
|
||||
NextResponse.json(await getData());
|
||||
return NextResponse.json({ total, pages });
|
||||
};
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { env } from "@/lib/env";
|
||||
import { EyeIcon } from "lucide-react";
|
||||
import Link from "@/components/link";
|
||||
import Time from "@/components/time";
|
||||
import { getFrontMatter } from "@/lib/posts";
|
||||
import { getFrontMatter, getViews } from "@/lib/posts";
|
||||
import { createMetadata } from "@/lib/metadata";
|
||||
import authorConfig from "@/lib/config/author";
|
||||
import { POSTS_DIR } from "@/lib/config/constants";
|
||||
import type { ReactElement } from "react";
|
||||
import type { FrontMatter } from "@/lib/posts";
|
||||
|
||||
export const revalidate = 600; // 10 minutes
|
||||
|
||||
export const metadata = createMetadata({
|
||||
title: "Notes",
|
||||
description: `Recent posts by ${authorConfig.name}.`,
|
||||
@@ -15,14 +19,18 @@ export const metadata = createMetadata({
|
||||
|
||||
const Page = async () => {
|
||||
// parse the year of each post and group them together
|
||||
const posts = await getFrontMatter();
|
||||
const [posts, views] = await Promise.all([getFrontMatter(), getViews()]);
|
||||
|
||||
const postsByYear: {
|
||||
[year: string]: FrontMatter[];
|
||||
[year: string]: (FrontMatter & { views: number })[];
|
||||
} = {};
|
||||
|
||||
posts.forEach((post) => {
|
||||
const year = new Date(post.date).getUTCFullYear();
|
||||
(postsByYear[year] || (postsByYear[year] = [])).push(post);
|
||||
(postsByYear[year] || (postsByYear[year] = [])).push({
|
||||
...post,
|
||||
views: views[post.slug] || 0,
|
||||
});
|
||||
});
|
||||
|
||||
const sections: ReactElement[] = [];
|
||||
@@ -31,17 +39,25 @@ const Page = async () => {
|
||||
sections.push(
|
||||
<section className="my-8 first-of-type:mt-0" key={year}>
|
||||
<h2 className="mt-0 mb-4 text-3xl font-bold md:text-4xl">{year}</h2>
|
||||
<ul>
|
||||
{posts.map(({ slug, date, title, htmlTitle }) => (
|
||||
<li className="mb-4 flex text-base leading-relaxed last-of-type:mb-0" key={slug}>
|
||||
<Time date={date} format="MMM d" className="text-muted-foreground w-22 shrink-0" />
|
||||
<span>
|
||||
<ul className="space-y-4">
|
||||
{posts.map(({ slug, date, title, htmlTitle, views }) => (
|
||||
<li className="flex text-base leading-relaxed" key={slug}>
|
||||
<Time date={date} format="MMM d" className="text-muted-foreground w-18 shrink-0 md:w-22" />
|
||||
<div className="space-x-2.5">
|
||||
<Link
|
||||
dynamicOnHover
|
||||
href={`/${POSTS_DIR}/${slug}`}
|
||||
dangerouslySetInnerHTML={{ __html: htmlTitle || title }}
|
||||
/>
|
||||
</span>
|
||||
{views > 0 && (
|
||||
<span className="bg-muted text-muted-foreground inline-flex h-5 flex-nowrap items-center space-x-1 rounded-md px-1.5 align-text-top text-xs font-semibold text-nowrap select-none">
|
||||
<EyeIcon className="inline-block size-4 shrink-0" />
|
||||
<span className="inline-block leading-5">
|
||||
{Intl.NumberFormat(env.NEXT_PUBLIC_SITE_LOCALE).format(views)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
47
lib/posts.ts
47
lib/posts.ts
@@ -1,5 +1,6 @@
|
||||
import { env } from "@/lib/env";
|
||||
import { cache } from "react";
|
||||
import { kv } from "@vercel/kv";
|
||||
import path from "path";
|
||||
import fs from "fs/promises";
|
||||
import glob from "fast-glob";
|
||||
@@ -43,7 +44,6 @@ export const getSlugs = cache(async (): Promise<string[]> => {
|
||||
return slugs;
|
||||
});
|
||||
|
||||
// overloaded to return either the front matter of a single post or ALL posts
|
||||
export const getFrontMatter: {
|
||||
/**
|
||||
* Parses and returns the front matter of ALL posts, sorted reverse chronologically
|
||||
@@ -112,6 +112,51 @@ export const getFrontMatter: {
|
||||
}
|
||||
);
|
||||
|
||||
export const getViews: {
|
||||
/**
|
||||
* Retrieves the number of views for ALL posts
|
||||
*/
|
||||
(): Promise<Record<string, number>>;
|
||||
/**
|
||||
* Retrieves the number of views for a given slug, or undefined if the slug does not exist
|
||||
*/
|
||||
(slug: string): Promise<number | 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") {
|
||||
const views = await kv.get<string>(`hits:${slug}`);
|
||||
|
||||
return views ? parseInt(views, 10) : undefined;
|
||||
}
|
||||
|
||||
if (!slug) {
|
||||
const slugs = await kv.scan(0, {
|
||||
match: "hits:*",
|
||||
type: "string",
|
||||
// set an arbitrary yet generous upper limit, just in case...
|
||||
count: 99,
|
||||
});
|
||||
|
||||
// get the value (number of hits) for each key (the slug of the page)
|
||||
const values = await kv.mget<string[]>(...slugs[1]);
|
||||
|
||||
const pages: Record<string, number> = {};
|
||||
|
||||
// pair the slugs with their hit values
|
||||
slugs[1].forEach(
|
||||
(slug, index) =>
|
||||
(pages[slug.split(":").pop()?.replace(`${POSTS_DIR}/`, "") as string] = parseInt(values[index], 10))
|
||||
);
|
||||
|
||||
return pages;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/** 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> => {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user