MCPcopy Create free account
hub / github.com/Datakitpage/Datakit / MemoryCache

Class MemoryCache

backend/api/src/postgres-proxy/utils/cache.util.ts:25–228  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

23}
24
25export class MemoryCache<T> {
26 private readonly logger = new Logger(MemoryCache.name);
27 private readonly cache = new Map<string, CacheEntry<T>>();
28 private readonly options: Required<CacheOptions>;
29 private cleanupInterval: NodeJS.Timeout;
30 private stats = {
31 hits: 0,
32 misses: 0,
33 };
34
35 constructor(options: CacheOptions = {}) {
36 this.options = {
37 ttl: options.ttl || 5 * 60 * 1000, // 5 minutes default
38 maxSize: options.maxSize || 1000,
39 enableStats: options.enableStats !== false,
40 };
41
42 // Cleanup interval every 5 minutes
43 this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);
44 }
45
46 /**
47 * Destroy the cache and clean up resources
48 */
49 destroy(): void {
50 if (this.cleanupInterval) {
51 clearInterval(this.cleanupInterval);
52 }
53 this.clear();
54 }
55
56 /**
57 * Gets a value from cache
58 */
59 get(key: string): T | null {
60 const entry = this.cache.get(key);
61
62 if (!entry) {
63 if (this.options.enableStats) {
64 this.stats.misses++;
65 }
66 return null;
67 }
68
69 // Check if expired
70 if (this.isExpired(entry)) {
71 this.cache.delete(key);
72 if (this.options.enableStats) {
73 this.stats.misses++;
74 }
75 return null;
76 }
77
78 // Update access info
79 entry.lastAccessed = Date.now();
80 entry.accessCount++;
81
82 if (this.options.enableStats) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected