+ Caching manually expire
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s

This commit is contained in:
Zakary Timson 2025-05-12 20:29:29 -04:00
parent d938996a66
commit 028b9c0f4c
2 changed files with 20 additions and 10 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.24.8", "version": "0.24.9",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@ -57,6 +57,11 @@ export class Cache<K extends string | number | symbol, T> {
return <K>value[this.key]; return <K>value[this.key];
} }
private save() {
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
}
/** /**
* Get all cached items * Get all cached items
* @return {T[]} Array of items * @return {T[]} Array of items
@ -105,8 +110,7 @@ export class Cache<K extends string | number | symbol, T> {
*/ */
delete(key: K) { delete(key: K) {
delete this.store[key]; delete this.store[key];
if(this.options.storageKey && this.options.storage) this.save();
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
} }
/** /**
@ -118,6 +122,16 @@ export class Cache<K extends string | number | symbol, T> {
.filter((v: any) => expired || !v._expired)); .filter((v: any) => expired || !v._expired));
} }
/**
* Manually expire a cached item
* @param {K} key Key to expire
*/
expire(key: K) {
this.complete = false;
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true;
else this.delete(key);
}
/** /**
* Get item from the cache * Get item from the cache
* @param {K} key Key to lookup * @param {K} key Key to lookup
@ -160,14 +174,10 @@ export class Cache<K extends string | number | symbol, T> {
set(key: K, value: T, ttl = this.options.ttl): this { set(key: K, value: T, ttl = this.options.ttl): this {
if(this.options.expiryPolicy == 'keep') delete (<any>this.store[key])._expired; if(this.options.expiryPolicy == 'keep') delete (<any>this.store[key])._expired;
this.store[key] = value; this.store[key] = value;
if(this.options.storageKey && this.options.storage) this.save();
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
if(ttl) setTimeout(() => { if(ttl) setTimeout(() => {
this.complete = false; this.expire(key);
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true; this.save();
else this.delete(key);
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
}, ttl * 1000); }, ttl * 1000);
return this; return this;
} }