Skip to content

Commit

Permalink
node-cache - adding setTtl() to NodeCacheStore (#789)
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredwray authored Sep 17, 2024
1 parent 7abf431 commit 0cb9bee
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/node-cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export type NodeCacheStoreOptions = {
* `del(key: string | number): Promise<boolean>` - Delete a key
* `mdel(keys: Array<string | number>): Promise<boolean>` - Delete multiple keys
* `clear(): Promise<void>` - Clear the cache
* `setTtl(key: string | number, ttl: number): Promise<boolean>` - Set the ttl of a key
* `stats`: `NodeCacheStats` - Get the stats of the cache
* `ttl`: `number` - The standard ttl as number in seconds for every generated cache element. 0 = unlimited
* `primary`: `Keyv` - The primary storage adapter
Expand Down
11 changes: 11 additions & 0 deletions packages/node-cache/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,15 @@ export class NodeCacheStore {
public async clear(): Promise<void> {
return this._cache.clear();
}

public async setTtl(key: string | number, ttl?: number): Promise<boolean> {
const finalTtl = ttl ?? this._cache.ttl;
const item = await this._cache.get(key.toString());
if (item) {
await this._cache.set(key.toString(), item, finalTtl);
return true;
}

return false;
}
}
13 changes: 13 additions & 0 deletions packages/node-cache/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,17 @@ describe('NodeCacheStore', () => {
expect(result1).toBeUndefined();
expect(result2).toBeUndefined();
});
test('should be able to set a key with ttl', async () => {
const store = new NodeCacheStore();
await store.set('test', 'value', 1000);
const result1 = await store.get('test');
expect(result1).toBe('value');
const result2 = await store.setTtl('test', 1000);
expect(result2).toBe(true);
});
test('should return false if no ttl is set', async () => {
const store = new NodeCacheStore();
const result1 = await store.setTtl('test', 1000);
expect(result1).toBe(false);
});
});

0 comments on commit 0cb9bee

Please sign in to comment.