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

save a redis query when fetching all view counts

This commit is contained in:
2025-05-06 20:24:55 -04:00
parent a08ec532b3
commit 0df56d127a
6 changed files with 40 additions and 32 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
import { CodeIcon, HomeIcon, MailIcon, PencilLineIcon, type LucideIcon } from "lucide-react";
import { HomeIcon, PencilLineIcon, CodeXmlIcon, MailIcon, type LucideIcon } from "lucide-react";
export type MenuItemConfig = {
text?: string;
@@ -20,7 +20,7 @@ export const menuItems: MenuItemConfig[] = [
{
text: "Projects",
href: "/projects",
icon: CodeIcon,
icon: CodeXmlIcon,
},
{
text: "Contact",
+23 -18
View File
@@ -128,32 +128,37 @@ export const getViews: {
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
Promise<any> => {
if (typeof slug === "string") {
const views = await kv.get<string>(`hits:${slug}`);
try {
const views = await kv.get<string>(`hits:${POSTS_DIR}/${slug}`);
return views ? parseInt(views, 10) : undefined;
return views ? parseInt(views, 10) : undefined;
} catch (error) {
console.error(`Failed to retrieve view count for post with slug "${slug}":`, error);
return 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,
});
try {
const allSlugs = await getSlugs();
const pages: Record<string, number> = {};
// get the value (number of hits) for each key (the slug of the page)
const values = await kv.mget<string[]>(...slugs[1]);
// get the value (number of views) for each key (the slug of the page)
const values = await kv.mget<string[]>(...allSlugs.map((slug) => `hits:${POSTS_DIR}/${slug}`));
const pages: Record<string, number> = {};
// pair the slugs with their view counts
allSlugs.forEach(
(slug, index) => (pages[slug.replace(`hits:${POSTS_DIR}/`, "")] = parseInt(values[index], 10))
);
// 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;
return pages;
} catch (error) {
console.error("Failed to retrieve view counts:", error);
return undefined;
}
}
throw new Error("getViews() called with invalid argument.");
}
);