Files
infohliadka/lib/cache.ts

79 lines
1.6 KiB
TypeScript

// Simple in-memory cache implementation (Redis simulation for development)
// In production, this would be replaced with actual Redis client
interface CacheEntry {
value: any
expiry: number
}
class SimpleCache {
private cache = new Map<string, CacheEntry>()
set(key: string, value: any, ttlSeconds = 300): void {
const expiry = Date.now() + (ttlSeconds * 1000)
this.cache.set(key, { value, expiry })
}
get<T>(key: string): T | null {
const entry = this.cache.get(key)
if (!entry) return null
if (Date.now() > entry.expiry) {
this.cache.delete(key)
return null
}
return entry.value as T
}
del(key: string): void {
this.cache.delete(key)
}
clear(): void {
this.cache.clear()
}
// Clean expired entries
cleanup(): void {
const now = Date.now()
Array.from(this.cache.entries()).forEach(([key, entry]) => {
if (now > entry.expiry) {
this.cache.delete(key)
}
})
}
}
// Global cache instance
export const cache = new SimpleCache()
// Cleanup expired entries every 5 minutes
setInterval(() => {
cache.cleanup()
}, 5 * 60 * 1000)
export function getCacheKey(...parts: (string | number)[]): string {
return parts.join(':')
}
export async function cacheWrapper<T>(
key: string,
fetcher: () => Promise<T>,
ttl = 300
): Promise<T> {
// Try to get from cache first
const cached = cache.get<T>(key)
if (cached !== null) {
return cached
}
// Fetch fresh data
const data = await fetcher()
// Cache the result
cache.set(key, data, ttl)
return data
}