+ 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",
"version": "0.24.8",
"version": "0.24.9",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -57,6 +57,11 @@ export class Cache<K extends string | number | symbol, T> {
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
* @return {T[]} Array of items
@ -105,8 +110,7 @@ export class Cache<K extends string | number | symbol, T> {
*/
delete(key: K) {
delete this.store[key];
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
this.save();
}
/**
@ -118,6 +122,16 @@ export class Cache<K extends string | number | symbol, T> {
.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
* @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 {
if(this.options.expiryPolicy == 'keep') delete (<any>this.store[key])._expired;
this.store[key] = value;
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
this.save();
if(ttl) setTimeout(() => {
this.complete = false;
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true;
else this.delete(key);
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
this.expire(key);
this.save();
}, ttl * 1000);
return this;
}