Files
lensflix/lib/cache.ts
T

58 lines
1.4 KiB
TypeScript

import { and, eq } from "drizzle-orm";
import type { CardType } from "./cards";
import { getDb } from "./db";
import { cardCache } from "./db/schema";
export async function getCachedCard<T>(
movieId: number,
cardType: CardType,
): Promise<T | null> {
try {
const db = getDb();
const rows = await db
.select()
.from(cardCache)
.where(
and(eq(cardCache.movieId, movieId), eq(cardCache.cardType, cardType)),
)
.limit(1);
if (rows.length === 0) {
return null;
}
return rows[0].payload as T;
} catch (err) {
// DB may be unavailable in local dev (e.g. DATABASE_URL points to Docker 'db' host).
// Treat as cache miss so card generation can still proceed via LLM.
console.warn(`[cache] getCachedCard(${movieId}, ${cardType}) skipped:`, err);
return null;
}
}
export async function setCachedCard<T>(
movieId: number,
cardType: CardType,
payload: T,
): Promise<void> {
try {
const db = getDb();
await db
.insert(cardCache)
.values({
movieId,
cardType,
payload,
})
.onConflictDoUpdate({
target: [cardCache.movieId, cardCache.cardType],
set: {
payload,
createdAt: new Date(),
},
});
} catch (err) {
console.warn(`[cache] setCachedCard(${movieId}, ${cardType}) skipped:`, err);
}
}