amanfor18's picture
Upload 15 files
21011e9 verified
Raw
History Blame Contribute Delete
2.4 kB
const { MongoClient } = require("mongodb");
let dbClient = null;
let dbInstance = null;
let cache = null;
let isSaving = false;
let needsSave = false;
const DEFAULT_DB = {
users: {}, // { userId: { username, coins, characters: [], totalWins } }
customCharacters: [], // admin-added characters
sessions: {}, // { chatId: session data }
};
async function initDB() {
const uri = process.env.MONGODB_URI;
if (!uri) {
console.error("❌ MONGODB_URI not set in environment!");
process.exit(1);
}
try {
console.log("πŸ”Œ Connecting to MongoDB...");
dbClient = new MongoClient(uri);
await dbClient.connect();
dbInstance = dbClient.db();
console.log("βœ… Successfully connected to MongoDB.");
const collection = dbInstance.collection("bot_state");
const record = await collection.findOne({ _id: "state" });
if (record) {
cache = record.data;
console.log("βœ… Loaded bot state from MongoDB cache.");
} else {
cache = JSON.parse(JSON.stringify(DEFAULT_DB));
await collection.insertOne({ _id: "state", data: cache });
console.log("βœ… Created initial bot state in MongoDB.");
}
} catch (err) {
console.error("❌ Failed to connect or initialize MongoDB:", err);
process.exit(1);
}
}
function loadDB() {
if (!cache) {
// Return temporary default during fallback
return JSON.parse(JSON.stringify(DEFAULT_DB));
}
return cache;
}
function saveDB(db) {
cache = db;
queueSave();
}
function queueSave() {
if (isSaving) {
needsSave = true;
return;
}
isSaving = true;
const collection = dbInstance.collection("bot_state");
collection.updateOne(
{ _id: "state" },
{ $set: { data: cache } },
{ upsert: true }
).then(() => {
isSaving = false;
console.log("πŸ’Ύ Bot state successfully synchronized to MongoDB.");
if (needsSave) {
needsSave = false;
queueSave();
}
}).catch((err) => {
console.error("❌ MongoDB background sync error:", err);
isSaving = false;
});
}
function getUser(db, userId, username) {
if (!db.users[userId]) {
db.users[userId] = {
username: username || `User${userId}`,
coins: 0,
characters: [],
totalWins: 0,
};
} else if (username) {
db.users[userId].username = username;
}
return db.users[userId];
}
module.exports = { initDB, loadDB, saveDB, getUser };