Files
EpicNext-Cms/src/lib/redis-cache.ts
T
2026-07-20 14:47:05 +02:00

52 lines
1010 B
TypeScript

import "server-only";
import { redis } from "@/lib/redis";
/**
* Cache the result of a fetch function in Redis.
* Falls back to the fresh fetch if Redis is unavailable.
*/
export async function redisCache<T>(
key: string,
ttlSeconds: number,
fetch: () => Promise<T>,
): Promise<T> {
if (!redis) return fetch();
try {
const cached = await redis.get(key);
if (cached !== null) {
return JSON.parse(cached) as T;
}
} catch {
// cache miss or error — fall through to fresh fetch
}
const fresh = await fetch();
try {
await redis.setex(key, ttlSeconds, JSON.stringify(fresh));
} catch {
// ignore write errors
}
return fresh;
}
// TODO: Check of dit weg kan — niet geïmporteerd in de codebase
export async function invalidateCache(key: string): Promise<void> {
if (!redis) return;
try {
await redis.del(key);
} catch {
// ignore
}
}
/**
* Build a namespaced cache key for API routes.
*/
export function apiCacheKey(path: string): string {
return `api:${path}`;
}