Files
buildpath/frontend/server/api/stats.ts
Valentin Haudiquet 0224b7812c
All checks were successful
pipeline / lint-and-format (push) Successful in 4m22s
pipeline / build-and-push-images (push) Successful in 2m14s
fix: pre-compute stats to make the API endpoint fast
2026-05-14 00:02:23 +02:00

59 lines
1.7 KiB
TypeScript

import type { MongoClient } from 'mongodb'
import { connectToDatabase, fetchLatestPatch, getAvailablePlatforms } from '../utils/mongo'
interface StatsDocument {
patch: string
total: number
platforms: Record<string, number>
updatedAt: Date
}
async function fetchGameCount(client: MongoClient, patch: string) {
const database = client.db('matches')
const statsCollection = database.collection<StatsDocument>('stats')
// Try to get stats from the pre-computed stats collection
const stats = await statsCollection.findOne({ patch })
if (stats) {
return { total: stats.total, platforms: stats.platforms }
}
// Fallback: compute stats from collections if stats document doesn't exist
// This handles the migration case where stats weren't pre-computed
const platforms = await getAvailablePlatforms(client, patch)
if (platforms.length > 0) {
let totalCount = 0
const platformCounts: Record<string, number> = {}
for (const platform of platforms) {
const collection = database.collection(`${patch}_${platform}`)
const count = await collection.countDocuments()
platformCounts[platform] = count
totalCount += count
}
return { total: totalCount, platforms: platformCounts }
}
// Fall back to old format (single collection)
const matches = database.collection(patch)
const count = await matches.countDocuments()
return { total: count, platforms: {} }
}
export default defineEventHandler(async _ => {
const client = await connectToDatabase()
const latestPatch = await fetchLatestPatch(client)
const gameCountData = await fetchGameCount(client, latestPatch)
await client.close()
return {
patch: latestPatch,
count: gameCountData.total,
platformCounts: gameCountData.platforms
}
})