MCPcopy Create free account
hub / github.com/Devographics/Monorepo / getFromCache

Function getFromCache

shared/fetch/fetch.ts:219–322  ·  view source on GitHub ↗
({
    key,
    fetchFunction: fetchFromSource,
    calledFrom,
    redisUrl,
    redisToken,
    shouldGetFromCache: shouldGetFromCacheOptions = true,
    shouldUpdateCache: shouldUpdateCacheOptions = true,
    shouldThrow = true,
    shouldCompress = false,
    cacheType = CacheType.REDIS
}: GetFromCacheOptions<T>)

Source from the content-addressed store, hash-verified

217 * @returns
218 */
219export async function getFromCache<T = any>({
220 key,
221 fetchFunction: fetchFromSource,
222 calledFrom,
223 redisUrl,
224 redisToken,
225 shouldGetFromCache: shouldGetFromCacheOptions = true,
226 shouldUpdateCache: shouldUpdateCacheOptions = true,
227 shouldThrow = true,
228 shouldCompress = false,
229 cacheType = CacheType.REDIS
230}: GetFromCacheOptions<T>) {
231 const startAt = new Date()
232 let inMemory = false
233 initRedis(redisUrl, redisToken)
234 const calledFromLog = calledFrom ? `(↪️ ${calledFrom})` : ''
235
236 const cacheIsDisabled = process.env.DISABLE_CACHE === 'true'
237 const shouldGetFromCache = !cacheIsDisabled && shouldGetFromCacheOptions
238 const shouldUpdateCache = !cacheIsDisabled && shouldUpdateCacheOptions
239
240 if (cacheIsDisabled && shouldGetFromCache === true) {
241 console.warn(
242 'Cache is turned off in env settings, ignoring shouldGetFromCache = true option'
243 )
244 }
245 if (cacheIsDisabled && shouldUpdateCache === true) {
246 console.warn(
247 'Cache is turned off in env settings, ignoring shouldUpdateCache = true option'
248 )
249 }
250
251 async function fetchAndProcess<T>(source: SourceType) {
252 const data = await fetchFromSource()
253 return processFetchData<T>(data, source, key)
254 }
255
256 let resultPromise: Promise<FetchPayload<T>>
257
258 try {
259 // 1. we have the a promise that resolve to the data in memory => return that
260 if (shouldGetFromCache && memoryCache.has(key)) {
261 console.debug(`🟢 [${key}] in-memory cache hit ${calledFromLog}`)
262 inMemory = true
263 resultPromise = memoryCache.get<Promise<FetchPayload<T>>>(key)!
264 } else {
265 // 2. store a promise that will first look in Redis, then in the main db
266 if (shouldGetFromCache) {
267 resultPromise = getFromCacheOrSource<T>({
268 key,
269 fetchFromSource,
270 calledFromLog,
271 shouldUpdateCache,
272 shouldCompress
273 })
274 } else {
275 console.debug(
276 `🟡 [${key}] Redis cache disabled, fetching from source ${calledFromLog}`

Callers

nothing calls this directly

Calls 5

initRedisFunction · 0.90
logToFileFunction · 0.90
getFromCacheOrSourceFunction · 0.85
fetchAndProcessFunction · 0.85
setResultSourceFunction · 0.85

Tested by

no test coverage detected