@@ -7,6 +7,7 @@ export type Cache = {
77 /**
88 * Atomically increments the value at key by 1 and returns the new value.
99 * If the key doesn't exist, it's set to 1.
10+ * The TTL is reset when the key is first created, not on subsequent increments.
1011 * @param key - The cache key
1112 * @param ttl - Time to live in seconds
1213 * @returns The new value after incrementing
@@ -49,14 +50,23 @@ export class MemoryCache implements Cache {
4950 incr ( key : string , ttl = 60 ) : number {
5051 const item = this . cache . get ( key ) ;
5152 const currentValue =
52- item && item . expires >= Date . now ( ) ? Number . parseInt ( item . value , 10 ) : 0 ;
53+ item && item . expires >= Date . now ( )
54+ ? Number . parseInt ( item . value , 10 ) || 0
55+ : 0 ;
5356 const newValue = currentValue + 1 ;
5457
55- this . cache . set ( key , {
56- value : String ( newValue ) ,
57- // biome-ignore lint/style/noMagicNumbers: 1000ms to seconds
58- expires : Date . now ( ) + ttl * 1000 ,
59- } ) ;
58+ if ( currentValue === 0 ) {
59+ this . cache . set ( key , {
60+ value : String ( newValue ) ,
61+ // biome-ignore lint/style/noMagicNumbers: 1000ms to seconds
62+ expires : Date . now ( ) + ttl * 1000 ,
63+ } ) ;
64+ } else if ( item ) {
65+ this . cache . set ( key , {
66+ value : String ( newValue ) ,
67+ expires : item . expires ,
68+ } ) ;
69+ }
6070
6171 return newValue ;
6272 }
@@ -90,7 +100,9 @@ export class RedisCache implements Cache {
90100 // Using a Lua script ensures both operations are atomic
91101 const script = `
92102 local count = redis.call('INCR', KEYS[1])
93- redis.call('EXPIRE', KEYS[1], ARGV[1])
103+ if count == 1 then
104+ redis.call('EXPIRE', KEYS[1], ARGV[1])
105+ end
94106 return count
95107 ` ;
96108
0 commit comments