From 028b9c0f4c54bab2ceebe7aa0ba4fbeb2947afaa Mon Sep 17 00:00:00 2001 From: ztimson Date: Mon, 12 May 2025 20:29:29 -0400 Subject: [PATCH] + Caching manually expire --- package.json | 2 +- src/cache.ts | 28 +++++++++++++++++++--------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 939bc2a..450137f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.24.8", + "version": "0.24.9", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/cache.ts b/src/cache.ts index 062a873..9dc2d73 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -57,6 +57,11 @@ export class Cache { return 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 { */ 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 { .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') (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 { set(key: K, value: T, ttl = this.options.ttl): this { if(this.options.expiryPolicy == 'keep') delete (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') (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; }