import { fetchStats } from '~~/server/admin.ts'; import { getLocale } from '~~/server/data.ts'; interface PublicStats { calculatedAt: number; overall: PublicLocaleStats; current: Partial; } interface PublicLocaleStats { users: number; cards: number; pageViews: number; visitors: number; online: number; visitDuration?: number; uptime?: number; responseTime?: number; } export default defineEventHandler(async (event) => { const requestedLocale = getLocale(event); const db = useDatabase(); const statsAll = await fetchStats(db); if (statsAll === null) { throw createError({ status: 404, statusMessage: 'Not Found', }); } const stats: PublicStats = { calculatedAt: statsAll.calculatedAt, overall: { users: statsAll.overall.users, cards: 0, pageViews: statsAll.overall.plausible?.pageviews || 0, visitors: statsAll.overall.plausible?.visitors || 0, online: statsAll.overall.plausible?.realTimeVisitors || 0, }, current: {}, }; for (const [locale, localeStats] of Object.entries(statsAll.locales)) { stats.overall.cards += localeStats.users; if (locale === requestedLocale) { stats.current = { cards: localeStats.users, }; } if (localeStats.plausible) { stats.overall.pageViews += localeStats.plausible.pageviews; stats.overall.visitors += localeStats.plausible.visitors; stats.overall.online += localeStats.plausible.realTimeVisitors; if (locale === requestedLocale) { stats.current.pageViews = localeStats.plausible.pageviews; stats.current.visitors = localeStats.plausible.visitors; stats.current.online = localeStats.plausible.realTimeVisitors; stats.current.visitDuration = localeStats.plausible.visit_duration; } } if (localeStats.heartbeat && locale === requestedLocale) { stats.current.uptime = localeStats.heartbeat.uptime; stats.current.responseTime = localeStats.heartbeat.avgResponseTime; } } return stats; });