1+ /**
2+ * Represents a cached item with its expiration timestamp.
3+ */
14type CacheItem < T > = {
25 value : T ;
36 expiresAt : number ;
47} ;
58
9+ /**
10+ * A Simple in-memory TTL(Time To Live) cache.
11+ *
12+ * Stores values in-process only and automatically removes expired entries.
13+ * This cache is not shared accross multiple server instances or severless invocations.
14+ *
15+ * @typeParam T - Type of values stored in the cache.
16+ */
617export class TTLCache < T > {
718 private store = new Map < string , CacheItem < T > > ( ) ;
819 private cleanupInterval : ReturnType < typeof setInterval > | null = null ;
920 private readonly maxSize ?: number ;
1021
22+ /**
23+ * Creates a new TTL cache instance.
24+ *
25+ * @param maxSize - Maximum number of items allowed in the cache.
26+ * @param cleanupIntervalMs - Interval in milliseconds for cleaning expired entries.
27+ */
1128 constructor ( maxSize ?: number , cleanupIntervalMs : number = 60000 ) {
1229 this . maxSize = maxSize === undefined ? undefined : Math . max ( 1 , maxSize ) ;
1330 const interval = Math . max ( 1000 , cleanupIntervalMs ) ;
@@ -35,6 +52,17 @@ export class TTLCache<T> {
3552 }
3653 }
3754
55+ /**
56+ * Retrieves a value from the cache.
57+ *
58+ * Returns 'null' if the key does not exist or if the entry has expired.
59+ *
60+ * @param key - Cache key.
61+ * @returns The cached value or 'null'.
62+ *
63+ * @example
64+ * const user = cache.get("user:1");
65+ */
3866 get ( key : string ) : T | null {
3967 const hit = this . store . get ( key ) ;
4068 if ( ! hit ) return null ;
@@ -47,6 +75,20 @@ export class TTLCache<T> {
4775 return hit . value ;
4876 }
4977
78+ /**
79+ * Stores a value in the cache with a TTL.
80+ *
81+ * If the cache reaches its maximum capacity, the oldest item
82+ * may be removed to make room for new entries.
83+ *
84+ * @param key - Cache key.
85+ * @param value - Value to cache.
86+ * @param ttlMs - Time to live in milliseconds.
87+ * @returns void
88+ *
89+ * @example
90+ * cache.set("user:1",userData,5000);
91+ */
5092 set ( key : string , value : T , ttlMs : number ) : void {
5193 // Capacity eviction (FIFO / LRU-lite)
5294 const maxSize = this . maxSize ;
@@ -64,10 +106,23 @@ export class TTLCache<T> {
64106 this . store . set ( key , { value, expiresAt : Date . now ( ) + ttlMs } ) ;
65107 }
66108
109+ /**
110+ * Removes all entries from the cache.
111+ *
112+ * @returns void
113+ *
114+ * @example
115+ * cache.clear();
116+ */
67117 clear ( ) : void {
68118 this . store . clear ( ) ;
69119 }
70120
121+ /**
122+ * Stops the cleanup interval and clears the cache.
123+ *
124+ * @returns void
125+ */
71126 destroy ( ) : void {
72127 if ( this . cleanupInterval ) {
73128 clearInterval ( this . cleanupInterval ) ;
0 commit comments