38 lines
846 B
TypeScript
38 lines
846 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,
|
|
})()
|
|
cacheLogger.debug(`'${key}' took ${(performance.now() - perf).toFixed(2)}ms`)
|
|
|
|
return res
|
|
}
|