Files
veilix.app/src/core/domains/server.ts
T

54 lines
1.7 KiB
TypeScript
Raw Normal View History

2026-10-21 05:08:05 +02:00
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<DomainConfig[]> => {
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<DomainConfig[]> } | null = null
const activeDomains = (): Promise<DomainConfig[]> => {
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<DomainConfig | null> => {
const domains = await activeDomains()
return domains.find((domain) => domain.hostname === hostname) ?? null
})
/** Основной домен сайта нужного типа: на него ведут ссылки между сайтом и кабинетом */
export const getPrimaryDomain = cache(
async (site: SiteCode, app: DomainApp): Promise<DomainConfig | null> => {
const domains = await activeDomains()
return (
domains.find((domain) => domain.site === site && domain.app === app && domain.isPrimary) ??
null
)
},
)