import { MongoClient } from 'mongodb' // Available platforms for region-specific match data const PLATFORMS = ['EUW1', 'EUN1', 'NA1', 'KR'] as const type Platform = (typeof PLATFORMS)[number] async function connectToDatabase() { // Create a MongoClient with a MongoClientOptions object to set the Stable API version let uri = `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_HOST}` if ( process.env.MONGO_URI != undefined && process.env.MONGO_URI != null && process.env.MONGO_URI != '' ) { uri = process.env.MONGO_URI } const client = new MongoClient(uri) await client.connect() return client } /** * Get the latest patch from existing match collections in the database. * Collections are named like "15.1_EUW1", "15.2_NA1", etc. */ async function fetchLatestPatch(client: MongoClient): Promise { const matchesDb = client.db('matches') const collections = await matchesDb.listCollections().toArray() const collectionNames = collections.map(c => c.name) // Extract unique patch versions from collection names const patches = new Set() for (const name of collectionNames) { // Collection names are either "patch_platform" or just "patch" const patch = name.split('_')[0] if (patch && /^\d+\.\d+$/.test(patch)) { patches.add(patch) } } if (patches.size === 0) { throw new Error('No patch collections found in database') } // Sort patches and return the latest (highest version number) const sortedPatches = Array.from(patches).sort((a, b) => { const [aMajor, aMinor] = a.split('.').map(Number) const [bMajor, bMinor] = b.split('.').map(Number) if (aMajor !== bMajor) return bMajor - aMajor return bMinor - aMinor }) return sortedPatches[0] } /** * Get available platforms for a given patch by checking which match collections exist * Note: Match collections are platform-specific (e.g., "15.1_EUW1") * Champion collections are aggregated across all platforms (e.g., "15.1") */ async function getAvailablePlatforms(client: MongoClient, patch: string): Promise { const matchesDb = client.db('matches') const collections = await matchesDb.listCollections().toArray() const collectionNames = collections.map(c => c.name) const availablePlatforms: Platform[] = [] for (const platform of PLATFORMS) { if (collectionNames.includes(`${patch}_${platform}`)) { availablePlatforms.push(platform) } } return availablePlatforms } export { connectToDatabase, fetchLatestPatch, getAvailablePlatforms, PLATFORMS } export type { Platform }