1
1
import { Redis , type RedisOptions } from 'ioredis' ;
2
2
import { CommandKitPluginRuntime , RuntimePlugin } from 'commandkit' ;
3
- import { CacheProvider , setCacheProvider } from '@commandkit/cache' ;
3
+ import { CacheProvider , CacheEntry , setCacheProvider } from '@commandkit/cache' ;
4
4
5
5
export type Awaitable < T > = T | Promise < T > ;
6
6
export type SerializeFunction = ( value : any ) => Awaitable < string > ;
@@ -61,14 +61,20 @@ export class RedisCache extends CacheProvider {
61
61
* @param key The key to retrieve the value for.
62
62
* @returns The value stored in the cache, or `undefined` if it does not exist.
63
63
*/
64
- public async get < T > ( key : string ) : Promise < T | undefined > {
64
+ public async get < T > ( key : string ) : Promise < CacheEntry < T > | undefined > {
65
65
const value = await this . redis . get ( key ) ;
66
66
67
67
if ( value === null ) {
68
68
return undefined ;
69
69
}
70
70
71
- return this . deserialize ( value ) as T ;
71
+ const entry = this . deserialize ( value ) as CacheEntry < T > ;
72
+ if ( entry . ttl && Date . now ( ) > entry . ttl ) {
73
+ await this . delete ( key ) ;
74
+ return undefined ;
75
+ }
76
+
77
+ return entry ;
72
78
}
73
79
74
80
/**
@@ -78,7 +84,12 @@ export class RedisCache extends CacheProvider {
78
84
* @param ttl The time-to-live for the cache entry in milliseconds.
79
85
*/
80
86
public async set < T > ( key : string , value : T , ttl ?: number ) : Promise < void > {
81
- const serialized = this . serialize ( value ) ;
87
+ const entry : CacheEntry < T > = {
88
+ value,
89
+ ttl : ttl != null ? Date . now ( ) + ttl : undefined ,
90
+ } ;
91
+
92
+ const serialized = this . serialize ( entry ) ;
82
93
const finalValue =
83
94
serialized instanceof Promise ? await serialized : serialized ;
84
95
0 commit comments