Cache returns deep copies to prevent deletion mid-use
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 17s
Build / Publish Documentation (push) Successful in 54s

This commit is contained in:
Zakary Timson 2025-02-27 08:36:30 -05:00
parent a3b34ef03f
commit 5b9e0714ce
2 changed files with 10 additions and 8 deletions

View File

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

View File

@ -1,3 +1,5 @@
import {deepCopy} from './objects.ts';
export type CacheOptions = { export type CacheOptions = {
/** Delete keys automatically after x amount of seconds */ /** Delete keys automatically after x amount of seconds */
ttl?: number; ttl?: number;
@ -36,12 +38,12 @@ export class Cache<K extends string | number | symbol, T> {
} }
return new Proxy(this, { return new Proxy(this, {
get: (target: this, prop: string | symbol) => { get: (target: this, prop: string | symbol) => {
if (prop in target) return (target as any)[prop]; if(prop in target) return (target as any)[prop];
return target.store[prop as K]; return deepCopy(target.store[prop as K]);
}, },
set: (target: this, prop: string | symbol, value: any) => { set: (target: this, prop: string | symbol, value: any) => {
if (prop in target) (target as any)[prop] = value; if(prop in target) (target as any)[prop] = value;
else target.store[prop as K] = value; else this.set(prop as K, value);
return true; return true;
} }
}); });
@ -58,7 +60,7 @@ export class Cache<K extends string | number | symbol, T> {
* @return {T[]} Array of items * @return {T[]} Array of items
*/ */
all(): T[] { all(): T[] {
return Object.values(this.store); return deepCopy(Object.values(this.store));
} }
/** /**
@ -119,7 +121,7 @@ export class Cache<K extends string | number | symbol, T> {
* @return {T} Cached item * @return {T} Cached item
*/ */
get(key: K): T { get(key: K): T {
return this.store[key]; return deepCopy(this.store[key]);
} }
/** /**
@ -137,7 +139,7 @@ export class Cache<K extends string | number | symbol, T> {
* @return {Record<K, T>} * @return {Record<K, T>}
*/ */
map(): Record<K, T> { map(): Record<K, T> {
return structuredClone(this.store); return deepCopy(this.store);
} }
/** /**