From cc8aefd280f0c0064345bc98312e1ad94f20c5b2 Mon Sep 17 00:00:00 2001 From: alkeicam Date: Wed, 30 Apr 2025 11:56:48 +0200 Subject: [PATCH 1/2] adding capability to clone cache items when retrieving from cache. --- packages/storage-memory/src/index.ts | 17 +++++++++++++++-- packages/storage-memory/src/memory-types.ts | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 packages/storage-memory/src/memory-types.ts diff --git a/packages/storage-memory/src/index.ts b/packages/storage-memory/src/index.ts index 00a0b1d..ed57370 100644 --- a/packages/storage-memory/src/index.ts +++ b/packages/storage-memory/src/index.ts @@ -1,12 +1,25 @@ import { ICacheItem, IStorage } from "node-ts-cache" +import { IMemoryCacheOptions } from "./memory-types" +export * from "./memory-types" export class MemoryStorage implements IStorage { private memCache: any = {} + private shouldClone: boolean = false; // by default no cloning (default behaviour) - constructor() {} + constructor(options?:IMemoryCacheOptions) { + if(options){ + this.shouldClone = options.clone + } + } public async getItem(key: string): Promise { - return this.memCache[key] + let response; + if(this.shouldClone){ + response = JSON.parse(JSON.stringify(this.memCache[key])); + }else{ + response = this.memCache[key] + } + return response; } public async setItem(key: string, content: any): Promise { diff --git a/packages/storage-memory/src/memory-types.ts b/packages/storage-memory/src/memory-types.ts new file mode 100644 index 0000000..45552e4 --- /dev/null +++ b/packages/storage-memory/src/memory-types.ts @@ -0,0 +1,3 @@ +export interface IMemoryCacheOptions { + clone: boolean // when set to true data returned from cache will be deep copied (deep copy will be returned) +} \ No newline at end of file From 8c3bad67ab7b3a62dc69f79970cc2a5e4b534054 Mon Sep 17 00:00:00 2001 From: alkeicam Date: Thu, 1 May 2025 08:25:28 +0200 Subject: [PATCH 2/2] Null/Undefined handling Making sure that if there is no cache item clone is not performed. --- packages/storage-memory/src/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/storage-memory/src/index.ts b/packages/storage-memory/src/index.ts index ed57370..4a1567f 100644 --- a/packages/storage-memory/src/index.ts +++ b/packages/storage-memory/src/index.ts @@ -15,7 +15,8 @@ export class MemoryStorage implements IStorage { public async getItem(key: string): Promise { let response; if(this.shouldClone){ - response = JSON.parse(JSON.stringify(this.memCache[key])); + const cacheData = this.memCache[key]; + response = cacheData?JSON.parse(JSON.stringify(this.memCache[key])):cacheData; }else{ response = this.memCache[key] }