Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});