Files
web/apps/scandic-web/services/dataCache/MemoryCache/UnstableCache/cacheOrGet.ts
Joakim Jäderberg 196ea2994f Merged in fix/warmup-autocomplete-data (pull request #2212)
warmup autocomplete data

* warmup autocomplete data


Approved-by: Anton Gunnarsson
2025-05-26 08:23:20 +00:00

44 lines
1023 B
TypeScript

import { revalidateTag, unstable_cache } from "next/cache"
import {
type CacheTime,
type DataCache,
getCacheTimeInSeconds,
} from "@/services/dataCache/Cache"
import {
type CacheOrGetOptions,
shouldGetFromCache,
} from "../../cacheOrGetOptions"
import { cacheLogger } from "../../logger"
export const cacheOrGet: DataCache["cacheOrGet"] = async <T>(
key: string | string[],
callback: () => Promise<T>,
ttl: CacheTime,
opts?: CacheOrGetOptions
): Promise<T> => {
if (!Array.isArray(key)) {
key = [key]
}
const perf = performance.now()
if (!shouldGetFromCache(opts)) {
revalidateTag(key[0])
}
const res = await unstable_cache(callback, key, {
revalidate: getCacheTimeInSeconds(ttl),
tags: key,
})()
const size = JSON.stringify(res).length / (1024 * 1024)
cacheLogger.debug(`'${key}': ${size}mb`)
if (size > 5) {
cacheLogger.warn(`'${key}' is larger than 5mb!`)
}
cacheLogger.debug(`'${key}' took ${(performance.now() - perf).toFixed(2)}ms`)
return res
}