Skip to content

Commit 3792cdb

Browse files
committed
✨ Add cache helper (#1995)
1 parent 8e223e6 commit 3792cdb

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/lib/clients/cache_strategy.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { Cache } from '$lib/clients/cache';
2+
3+
/**
4+
* Utility class for managing cached data for contest tasks.
5+
* Provides a mechanism to either retrieve data from cache if available
6+
* or fetch it using the provided function.
7+
*/
8+
export class ContestTaskCache {
9+
/**
10+
* Retrieves data from cache if available, otherwise fetches it using the provided function.
11+
*
12+
* @template T - The type of data being cached and returned
13+
* @param {string} key - The unique identifier for the cached data
14+
* @param {() => Promise<T>} fetchFunction - Function that returns a Promise resolving to data of type T
15+
* @param {Cache<T>} cache - Cache object with get and set methods for type T
16+
* @returns {Promise<T>} - The cached data or newly fetched data
17+
*
18+
* @example
19+
* const result = await cacheInstance.getCachedOrFetch(
20+
* 'contests-123',
21+
* () => api.fetchContests(),
22+
* contestCache
23+
* );
24+
*/
25+
async getCachedOrFetch<T>(
26+
key: string,
27+
fetchFunction: () => Promise<T>,
28+
cache: Cache<T>,
29+
): Promise<T> {
30+
const cachedData = cache.get(key);
31+
32+
if (cachedData) {
33+
console.log(`Using cached data for ${key}`);
34+
return cachedData;
35+
}
36+
37+
try {
38+
const contestTasks = await fetchFunction();
39+
cache.set(key, contestTasks);
40+
41+
return contestTasks;
42+
} catch (error) {
43+
console.error(`Failed to fetch contests and/or tasks for ${key}:`, error);
44+
return [] as unknown as T;
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)