Skip to content

Commit 904c610

Browse files
committed
fix: redis cache provider
1 parent 5afe192 commit 904c610

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

packages/redis/src/index.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Redis, type RedisOptions } from 'ioredis';
22
import { CommandKitPluginRuntime, RuntimePlugin } from 'commandkit';
3-
import { CacheProvider, setCacheProvider } from '@commandkit/cache';
3+
import { CacheProvider, CacheEntry, setCacheProvider } from '@commandkit/cache';
44

55
export type Awaitable<T> = T | Promise<T>;
66
export type SerializeFunction = (value: any) => Awaitable<string>;
@@ -61,14 +61,20 @@ export class RedisCache extends CacheProvider {
6161
* @param key The key to retrieve the value for.
6262
* @returns The value stored in the cache, or `undefined` if it does not exist.
6363
*/
64-
public async get<T>(key: string): Promise<T | undefined> {
64+
public async get<T>(key: string): Promise<CacheEntry<T> | undefined> {
6565
const value = await this.redis.get(key);
6666

6767
if (value === null) {
6868
return undefined;
6969
}
7070

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;
7278
}
7379

7480
/**
@@ -78,7 +84,12 @@ export class RedisCache extends CacheProvider {
7884
* @param ttl The time-to-live for the cache entry in milliseconds.
7985
*/
8086
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);
8293
const finalValue =
8394
serialized instanceof Promise ? await serialized : serialized;
8495

0 commit comments

Comments
 (0)