import { MongoClient, Db, Collection, Document, UpdateResult, DeleteResult, } from 'mongodb'; import config from '../../../config'; let client: MongoClient; let database: Db; let collection: Collection; async function initializeDbConnection() { if (!client) { client = new MongoClient(config.mongodbUri); await client.connect(); database = client.db('butler_db'); collection = database.collection('GameFeatures'); } } /** * Retrieves a list of game names from the database. * * @returns An array of game objects containing game names. */ export async function listGameNames(): Promise { await initializeDbConnection(); return collection.find({}, { projection: { game: 1 } }).toArray(); } /** * Retrieves a specific game by its name from the database. * * @param game - The name of the game to retrieve. * @returns The game object if found, or null if not found. */ export async function getGame(game: string): Promise { await initializeDbConnection(); return collection.findOne({ game }); } /** * Sets a key-value pair for a specific game in the database. * If the game does not exist, it will be created. * * @param game - The name of the game to update or create. * @param key - The key to set or update in the game object. * @param value - The value to set for the specified key. * @returns The result of the update operation. */ export async function setGame( game: string, key: string, value: any ): Promise { await initializeDbConnection(); return collection.updateOne( { game }, { $set: { game, [key]: value } }, { upsert: true } ); } /** * Deletes a game from the database by its name. * * @param game - The name of the game to delete. * @returns The result of the delete operation. */ export async function deleteGame(game: string): Promise { await initializeDbConnection(); return collection.deleteOne({ game }); } /** * Deletes a specific field from a game object in the database. * * @param game - The name of the game to update. * @param key - The field key to remove from the game object. * @returns The result of the update operation. */ export async function deleteField( game: string, key: string ): Promise { await initializeDbConnection(); return collection.updateOne({ game }, { $unset: { [key]: '' } }); }