-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
export class CacheSingleton { | ||
private static instance: CacheSingleton | ||
private cache: Map<string, any> | ||
|
||
private constructor() { | ||
this.cache = new Map<string, any>() | ||
} | ||
|
||
public static getInstance(): CacheSingleton { | ||
if (!CacheSingleton.instance) { | ||
CacheSingleton.instance = new CacheSingleton() | ||
} | ||
return CacheSingleton.instance | ||
} | ||
|
||
public set(key: string, value: any): void { | ||
this.cache.set(key, value) | ||
} | ||
|
||
public get(key: string): any { | ||
return this.cache.get(key) | ||
} | ||
|
||
// Optionally, you can add methods to clear the cache or check if a key exists | ||
public clear(): void { | ||
this.cache.clear() | ||
} | ||
|
||
public has(key: string): boolean { | ||
return this.cache.has(key) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { CacheSingleton } from './cache-singleton' | ||
|
||
export class CacheUtils { | ||
private static cache = CacheSingleton.getInstance() | ||
|
||
public static async getOrSetCache<T>(key: string, fetchData: () => Promise<T>): Promise<T> { | ||
let data = this.cache.get(key) | ||
if (!data) { | ||
data = await fetchData() | ||
this.cache.set(key, data) | ||
} | ||
return data | ||
} | ||
} |