import config from '@payload-config' import { getPayload } from 'payload' import { cache } from 'react' import { type DomainApp, type DomainConfig, DOMAINS_TTL_MS, type SiteCode, toDomainConfig, } from './types' /** Активные домены из Payload */ export const listActiveDomains = async (): Promise => { const payload = await getPayload({ config }) const { docs } = await payload.find({ collection: 'domains', where: { active: { equals: true } }, depth: 1, pagination: false, overrideAccess: true, }) return docs.map(toDomainConfig).filter((domain) => domain !== null) } let cached: { at: number; domains: Promise } | null = null const activeDomains = (): Promise => { if (!cached || Date.now() - cached.at > DOMAINS_TTL_MS) { const domains = listActiveDomains() cached = { at: Date.now(), domains } domains.catch(() => { cached = null }) } return cached.domains } /** Домен по хосту для страниц; null — домена нет или он выключен */ export const getDomain = cache(async (hostname: string): Promise => { const domains = await activeDomains() return domains.find((domain) => domain.hostname === hostname) ?? null }) /** Основной домен сайта нужного типа: на него ведут ссылки между сайтом и кабинетом */ export const getPrimaryDomain = cache( async (site: SiteCode, app: DomainApp): Promise => { const domains = await activeDomains() return ( domains.find((domain) => domain.site === site && domain.app === app && domain.isPrimary) ?? null ) }, )