better caching

This commit is contained in:
Michael Freno
2025-12-22 17:38:08 -05:00
parent 11fad35288
commit 541ee5b8b2
3 changed files with 133 additions and 92 deletions

View File

@@ -1,10 +1,12 @@
import { createTRPCRouter, publicProcedure } from "../utils"; import { createTRPCRouter, publicProcedure } from "../utils";
import { ConnectionFactory } from "~/server/utils"; import { ConnectionFactory } from "~/server/utils";
import { withCache } from "~/server/cache"; import { withCacheAndStale } from "~/server/cache";
const BLOG_CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
export const blogRouter = createTRPCRouter({ export const blogRouter = createTRPCRouter({
getRecentPosts: publicProcedure.query(async () => { getRecentPosts: publicProcedure.query(async () => {
return withCache("recent-posts", 10 * 60 * 1000, async () => { return withCacheAndStale("blog-recent-posts", BLOG_CACHE_TTL, async () => {
// Get database connection // Get database connection
const conn = ConnectionFactory(); const conn = ConnectionFactory();
@@ -39,7 +41,10 @@ export const blogRouter = createTRPCRouter({
getPosts: publicProcedure.query(async ({ ctx }) => { getPosts: publicProcedure.query(async ({ ctx }) => {
const privilegeLevel = ctx.privilegeLevel; const privilegeLevel = ctx.privilegeLevel;
return withCache(`posts-${privilegeLevel}`, 5 * 60 * 1000, async () => { return withCacheAndStale(
`blog-posts-${privilegeLevel}`,
BLOG_CACHE_TTL,
async () => {
const conn = ConnectionFactory(); const conn = ConnectionFactory();
// Fetch all posts with aggregated data // Fetch all posts with aggregated data
@@ -91,6 +96,7 @@ export const blogRouter = createTRPCRouter({
}); });
return { posts, tags, tagMap, privilegeLevel }; return { posts, tags, tagMap, privilegeLevel };
}); }
);
}) })
}); });

View File

@@ -7,6 +7,9 @@ import { z } from "zod";
import { ConnectionFactory } from "~/server/utils"; import { ConnectionFactory } from "~/server/utils";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { env } from "~/env/server"; import { env } from "~/env/server";
import { cache, withCacheAndStale } from "~/server/cache";
const BLOG_CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
export const databaseRouter = createTRPCRouter({ export const databaseRouter = createTRPCRouter({
// ============================================================ // ============================================================
@@ -290,6 +293,10 @@ export const databaseRouter = createTRPCRouter({
}) })
) )
.query(async ({ input }) => { .query(async ({ input }) => {
return withCacheAndStale(
`blog-post-id-${input.id}`,
BLOG_CACHE_TTL,
async () => {
try { try {
const conn = ConnectionFactory(); const conn = ConnectionFactory();
// Single query with JOIN to get post and tags in one go // Single query with JOIN to get post and tags in one go
@@ -324,6 +331,8 @@ export const databaseRouter = createTRPCRouter({
message: "Failed to fetch post by ID" message: "Failed to fetch post by ID"
}); });
} }
}
);
}), }),
getPostByTitle: publicProcedure getPostByTitle: publicProcedure
@@ -334,6 +343,10 @@ export const databaseRouter = createTRPCRouter({
}) })
) )
.query(async ({ input, ctx }) => { .query(async ({ input, ctx }) => {
return withCacheAndStale(
`blog-post-title-${input.title}`,
BLOG_CACHE_TTL,
async () => {
try { try {
const conn = ConnectionFactory(); const conn = ConnectionFactory();
@@ -375,6 +388,8 @@ export const databaseRouter = createTRPCRouter({
message: "Failed to fetch post by title" message: "Failed to fetch post by title"
}); });
} }
}
);
}), }),
createPost: publicProcedure createPost: publicProcedure
@@ -422,6 +437,9 @@ export const databaseRouter = createTRPCRouter({
await conn.execute(tagQuery); await conn.execute(tagQuery);
} }
// Invalidate blog cache
cache.deleteByPrefix("blog-");
return { data: results.lastInsertRowid }; return { data: results.lastInsertRowid };
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -509,6 +527,9 @@ export const databaseRouter = createTRPCRouter({
await conn.execute(tagQuery); await conn.execute(tagQuery);
} }
// Invalidate blog cache
cache.deleteByPrefix("blog-");
return { data: results.lastInsertRowid }; return { data: results.lastInsertRowid };
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -549,6 +570,9 @@ export const databaseRouter = createTRPCRouter({
args: [input.id] args: [input.id]
}); });
// Invalidate blog cache
cache.deleteByPrefix("blog-");
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
console.error(error); console.error(error);

View File

@@ -48,6 +48,17 @@ class SimpleCache {
delete(key: string): void { delete(key: string): void {
this.cache.delete(key); this.cache.delete(key);
} }
/**
* Delete all keys starting with a prefix
*/
deleteByPrefix(prefix: string): void {
for (const key of this.cache.keys()) {
if (key.startsWith(prefix)) {
this.cache.delete(key);
}
}
}
} }
export const cache = new SimpleCache(); export const cache = new SimpleCache();