import 'server-only' import type { Config } from '@/payload-types' import configPromise from '@payload-config' import { revalidateTag, unstable_cache } from 'next/cache' import { getPayload } from 'payload' type Global = keyof Config['globals'] async function getGlobal(slug: Slug, depth?: number) { const payload = await getPayload({ config: configPromise }) const global = await payload.findGlobal({ slug, depth, }) return global } export const getGlobalCacheTag = (slug: string) => `global_${slug}` type CachedGlobalFactory = () => Promise const cachedGlobalFactories = new Map() export const getCachedGlobal = (slug: Slug, depth?: number) => { const tag = getGlobalCacheTag(slug) const cacheKey = `${tag}:${depth ?? 0}` const existing = cachedGlobalFactories.get(cacheKey) as CachedGlobalFactory | undefined if (existing) return existing const factory = unstable_cache(async () => getGlobal(slug, depth), [cacheKey], { tags: [tag], }) as CachedGlobalFactory cachedGlobalFactories.set(cacheKey, factory as CachedGlobalFactory) return factory } export const revalidateGlobal = (slug: Slug) => revalidateTag(getGlobalCacheTag(slug))