fix: pre-compute stats to make the API endpoint fast
This commit is contained in:
@@ -1,14 +1,29 @@
|
||||
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')
|
||||
|
||||
// Check for platform-specific collections
|
||||
// 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) {
|
||||
// Sum counts from all platform-specific collections
|
||||
let totalCount = 0
|
||||
const platformCounts: Record<string, number> = {}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user