import { MongoClient } from 'mongodb';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load configuration similar to the main server
let settings;
try {
const settingsPath = join(__dirname, "../settings.json");
const settingsContent = readFileSync(settingsPath, "utf8");
settings = JSON.parse(settingsContent);
} catch (error) {
console.error("Error reading settings.json:", error.message);
console.error("Using default settings...");
settings = {
mongodb: {
uri: "mongodb://localhost:27017",
database: "mcpserver"
}
};
}
class DatabaseManager {
constructor() {
this.client = null;
this.db = null;
this.isConnected = false;
}
async connect() {
try {
if (this.client && this.db && this.isConnected) {
return; // already connected
}
this.client = new MongoClient(settings.mongodb.uri, {
connectTimeoutMS: 10000,
maxPoolSize: 10,
});
await this.client.connect();
this.db = this.client.db(settings.mongodb.database);
// Test connection
await this.db.admin().ping();
this.isConnected = true;
console.error(`Connected to MongoDB database: ${settings.mongodb.database}`);
} catch (error) {
console.error('Failed to connect to MongoDB:', error);
this.isConnected = false;
throw error;
}
}
async ensureConnected() {
if (this.isConnected) return;
await this.connect();
}
async disconnect() {
if (this.client) {
await this.client.close();
this.client = null;
this.db = null;
this.isConnected = false;
console.error('Disconnected from MongoDB');
}
}
getDatabase() {
if (!this.db) {
throw new Error('Database not connected. Call connect() first.');
}
return this.db;
}
getMasterUserCollection() {
return this.getDatabase().collection('masterUser');
}
getInvoicesCollection() {
return this.getDatabase().collection('invoices');
}
async checkConnection() {
try {
if (!this.client || !this.isConnected) return false;
await this.client.db('admin').admin().ping();
return true;
} catch {
this.isConnected = false;
return false;
}
}
}
export const dbManager = new DatabaseManager();
export default dbManager;