MCPcopy Create free account
hub / github.com/pollinations/pollinations / cached

Function cached

shared/cache.ts:21–64  ·  view source on GitHub ↗
(
    fn: (...args: TArgs) => Promise<TReturn>,
    options: CacheOptions<TArgs>,
)

Source from the content-addressed store, hash-verified

19 * @returns A cached version of the function
20 */
21export function cached<TArgs extends unknown[], TReturn>(
22 fn: (...args: TArgs) => Promise<TReturn>,
23 options: CacheOptions<TArgs>,
24): (...args: TArgs) => Promise<TReturn> {
25 const { ttl, kv, keyGenerator, log } = options;
26
27 return async (...args: TArgs): Promise<TReturn> => {
28 const cacheKey = await keyGenerator(...args);
29
30 try {
31 log.trace("Fetching from cache: {key}", { key: cacheKey });
32 const cachedData = (await kv.get(
33 cacheKey,
34 "json",
35 )) as CacheEntry<TReturn> | null;
36 if (cachedData) {
37 const ttlChanged = cachedData.ttl !== ttl;
38 if (!ttlChanged) {
39 return cachedData.value;
40 }
41 }
42 } catch (error) {
43 log.warn("Failed to read from cache: {error}", { error });
44 }
45
46 log.trace("Executing function: {key}", { key: cacheKey });
47 const result = await fn(...args);
48
49 try {
50 log.trace("Writing to cache: {key}", { key: cacheKey });
51 const cacheEntry: CacheEntry<TReturn> = {
52 value: result,
53 ttl,
54 };
55 await kv.put(cacheKey, JSON.stringify(cacheEntry), {
56 expirationTtl: ttl,
57 });
58 } catch (error) {
59 log.warn("Failed to write to cache: {error}", { error });
60 }
61
62 return result;
63 };
64}

Callers 1

getModelStatsFunction · 0.90

Calls 6

fnFunction · 0.85
traceMethod · 0.80
warnMethod · 0.80
stringifyMethod · 0.80
getMethod · 0.65
putMethod · 0.65

Tested by

no test coverage detected