Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
e6636d373b | |||
811d797e1b |
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.16.4",
|
||||
"version": "0.16.6",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
23
src/cache.ts
23
src/cache.ts
@ -13,7 +13,19 @@ export class Cache<K, T> {
|
||||
* @param {keyof T} key Default property to use as primary key
|
||||
* @param {number} ttl Default expiry in milliseconds
|
||||
*/
|
||||
constructor(public readonly key: keyof T, public ttl?: number) { }
|
||||
constructor(public readonly key: keyof T, public ttl?: number) {
|
||||
return new Proxy(this, {
|
||||
get: (target: this, prop: string | symbol) => {
|
||||
if(prop in target) return (<any>target)[prop];
|
||||
return target.store[prop];
|
||||
},
|
||||
set: (target: any, prop: string | symbol, value: T) => {
|
||||
if(prop in target) target[prop] = value;
|
||||
else target.store[prop] = value;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getKey(value: T): K {
|
||||
return <K>value[this.key];
|
||||
@ -71,6 +83,15 @@ export class Cache<K, T> {
|
||||
return <[K, T][]>Object.entries(this.store);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item from the cache
|
||||
* @param {K} key Key to lookup
|
||||
* @return {T} Cached item
|
||||
*/
|
||||
get(key: K): T {
|
||||
return this.store[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of cached keys
|
||||
*
|
||||
|
Reference in New Issue
Block a user