From 5b9e0714ce8eec13a1b42988f9908df82714e206 Mon Sep 17 00:00:00 2001 From: ztimson Date: Thu, 27 Feb 2025 08:36:30 -0500 Subject: [PATCH] Cache returns deep copies to prevent deletion mid-use --- package.json | 2 +- src/cache.ts | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index e461e1a..f808fee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.23.12", + "version": "0.23.13", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/cache.ts b/src/cache.ts index 9d85c0a..a3ecee4 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -1,3 +1,5 @@ +import {deepCopy} from './objects.ts'; + export type CacheOptions = { /** Delete keys automatically after x amount of seconds */ ttl?: number; @@ -36,12 +38,12 @@ export class Cache { } return new Proxy(this, { get: (target: this, prop: string | symbol) => { - if (prop in target) return (target as any)[prop]; - return target.store[prop as K]; + if(prop in target) return (target as any)[prop]; + return deepCopy(target.store[prop as K]); }, set: (target: this, prop: string | symbol, value: any) => { - if (prop in target) (target as any)[prop] = value; - else target.store[prop as K] = value; + if(prop in target) (target as any)[prop] = value; + else this.set(prop as K, value); return true; } }); @@ -58,7 +60,7 @@ export class Cache { * @return {T[]} Array of items */ all(): T[] { - return Object.values(this.store); + return deepCopy(Object.values(this.store)); } /** @@ -119,7 +121,7 @@ export class Cache { * @return {T} Cached item */ get(key: K): T { - return this.store[key]; + return deepCopy(this.store[key]); } /** @@ -137,7 +139,7 @@ export class Cache { * @return {Record} */ map(): Record { - return structuredClone(this.store); + return deepCopy(this.store); } /**