Files
Linus Flood 1b35618eb2 Merged in feat/sw-3596-cache (pull request #3106)
feat(SW-3598): Don't call redis api if cachetime=0

* feat(SW-3596): no cache if ttl=0

* Fixed on set as well

* No cache if redemption

* Revert no cache if redemption


Approved-by: Joakim Jäderberg
2025-11-11 06:52:47 +00:00

57 lines
1.2 KiB
TypeScript

import {
type CacheTime,
type DataCache,
getCacheTimeInSeconds,
} from "../../Cache"
import {
type CacheOrGetOptions,
shouldGetFromCache,
} from "../../cacheOrGetOptions"
import { cacheLogger } from "../../logger"
import { get } from "./get"
import { set } from "./set"
export const cacheOrGet: DataCache["cacheOrGet"] = async <T>(
key: string | string[],
callback: (overrideTTL?: (cacheTime: CacheTime) => void) => Promise<T>,
ttl: CacheTime,
opts?: CacheOrGetOptions
): Promise<T> => {
if (Array.isArray(key)) {
key = key.join("-")
}
let realTTL = ttl
const overrideTTL = function (cacheTime: CacheTime) {
realTTL = cacheTime
}
if (getCacheTimeInSeconds(ttl) <= 0) {
cacheLogger.debug(`'Fetching ${key}' with ttl=0. Skipping cache!`)
return await callback(overrideTTL)
}
let cached: Awaited<T> | undefined = undefined
if (shouldGetFromCache(opts)) {
cached = await get(key)
if (cached) {
return cached
}
cacheLogger.debug(`Miss for key '${key}'`)
}
try {
const data = await callback(overrideTTL)
await set(key, data, realTTL)
return data
} catch (e) {
cacheLogger.error(
`Error while fetching data for key '${key}', avoid caching`,
e
)
throw e
}
}