@@ -19,6 +19,12 @@ export class TTLCache<T> {
1919 private cleanupInterval : ReturnType < typeof setInterval > | null = null ;
2020 private readonly maxSize ?: number ;
2121
22+ private static assertValidKey ( key : unknown ) : asserts key is string {
23+ if ( typeof key !== 'string' ) {
24+ throw new TypeError ( 'Cache key must be a string' ) ;
25+ }
26+ }
27+
2228 /**
2329 * Creates a new TTL cache instance.
2430 *
@@ -62,6 +68,8 @@ export class TTLCache<T> {
6268 * const user = cache.get("user:1");
6369 */
6470 get ( key : string ) : T | null {
71+ TTLCache . assertValidKey ( key ) ;
72+
6573 const hit = this . store . get ( key ) ;
6674 if ( ! hit ) return null ;
6775
@@ -87,6 +95,8 @@ export class TTLCache<T> {
8795 * }
8896 */
8997 has ( key : string ) : boolean {
98+ TTLCache . assertValidKey ( key ) ;
99+
90100 const hit = this . store . get ( key ) ;
91101 if ( ! hit ) return false ;
92102
@@ -109,6 +119,8 @@ export class TTLCache<T> {
109119 * cache.delete("user:1");
110120 */
111121 delete ( key : string ) : boolean {
122+ TTLCache . assertValidKey ( key ) ;
123+
112124 return this . store . delete ( key ) ;
113125 }
114126
@@ -134,13 +146,16 @@ export class TTLCache<T> {
134146 * @returns `true` if the entry existed and was updated, `false` if missing or expired.
135147 */
136148 update ( key : string , value : T ) : boolean {
149+ TTLCache . assertValidKey ( key ) ;
150+
137151 const hit = this . store . get ( key ) ;
138152 if ( ! hit || Date . now ( ) > hit . expiresAt ) return false ;
139153 hit . value = value ;
140154 return true ;
141155 }
142156
143157 set ( key : string , value : T , ttlMs : number ) : void {
158+ TTLCache . assertValidKey ( key ) ;
144159 if ( key === '' ) throw new Error ( 'Cache key cannot be empty' ) ;
145160 if ( ttlMs <= 0 ) throw new RangeError ( `ttlMs must be positive, got ${ ttlMs } ` ) ;
146161
0 commit comments