mirror of
https://github.com/trezor/trezor-suite.git
synced 2026-03-02 21:45:14 +01:00
feat(utils): cache with ttl
This commit is contained in:
committed by
Tomáš Klíma
parent
2f7a039ec8
commit
3c07bce818
30
packages/utils/src/cache.ts
Normal file
30
packages/utils/src/cache.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Cache class which allows to store Key-Value pairs with a TTL for each key
|
||||
*/
|
||||
export class Cache {
|
||||
store: Map<string, { value: any; ttl: number }>;
|
||||
|
||||
constructor() {
|
||||
this.store = new Map();
|
||||
}
|
||||
|
||||
set(key: string, value: any, ttl: number) {
|
||||
this.store.set(key, { value, ttl: Date.now() + ttl });
|
||||
}
|
||||
|
||||
get(key: string) {
|
||||
const entry = this.store.get(key);
|
||||
if (!entry) return;
|
||||
if (entry.ttl < Date.now()) {
|
||||
this.store.delete(key);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
delete(key: string) {
|
||||
this.store.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export * from './arrayPartition';
|
||||
export * from './arrayShuffle';
|
||||
export * from './arrayToDictionary';
|
||||
export * from './bytesToHumanReadable';
|
||||
export * from './cache';
|
||||
export * from './capitalizeFirstLetter';
|
||||
export * from './cloneObject';
|
||||
export * from './countBytesInString';
|
||||
|
||||
31
packages/utils/tests/cache.test.ts
Normal file
31
packages/utils/tests/cache.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Cache } from '../src/cache';
|
||||
|
||||
const delay = (ms: number) => jest.advanceTimersByTime(ms);
|
||||
|
||||
const TTL = 100;
|
||||
|
||||
describe('Cache', () => {
|
||||
let cache: Cache;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
cache = new Cache();
|
||||
});
|
||||
|
||||
it('set and get', () => {
|
||||
cache.set('key', 'value', TTL);
|
||||
expect(cache.get('key')).toEqual('value');
|
||||
});
|
||||
|
||||
it('get with expired TTL', () => {
|
||||
cache.set('key', 'value', TTL);
|
||||
delay(TTL + 1);
|
||||
expect(cache.get('key')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('delete', () => {
|
||||
cache.set('key', 'value', TTL);
|
||||
cache.delete('key');
|
||||
expect(cache.get('key')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user