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

display each post's view count in list

This commit is contained in:
2025-05-06 15:26:24 -04:00
parent 36e98ce720
commit bea2a55f77
3 changed files with 95 additions and 51 deletions
+46 -1
View File
@@ -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 {