import { MongoClient } from 'mongodb'; import * as config from '../config.js'; const client = new MongoClient(config.dbUri); class Database { constructor(dbname) { this.dbname = dbname; } async connect() { try { if (!client.isConnected) { await client.connect(); console.log("Connected to MongoDB"); } } catch (error) { console.error("Error connecting to MongoDB:", error.message); } } collection(collectionName) { try { const db = client.db(this.dbname); return db.collection(collectionName); } catch (error) { console.error("Error accessing collection:", error.message); } } async close() { try { await client.close(); console.log("MongoDB connection closed"); } catch (error) { console.error("Error closing MongoDB connection:", error.message); } } async IPAddressAndUpdate(ip) { try { const collection = this.collection("FastJsAPI"); const filter = { ip: ip }; const update = { $set: { ip: ip } }; const result = await collection.updateOne(filter, update, { upsert: true }); if (result.upsertedCount > 0) { console.log("Inserted a new IP address:", ip); } else { console.log("Updated an existing IP address:", ip); } } catch (error) { console.error("Error updating IP address:", error.message); } } async UnblockedIp(ip) { try { const collection = this.collection("FastJsAPI"); const filter = { ip: ip }; const update = { $set: { blocked: false } }; const result = await collection.updateOne(filter, update, { upsert: true }); if (result.upsertedCount > 0) { console.log("IP address unblocked:", ip); } else { console.log("Updated an existing IP address:", ip); } } catch (error) { console.error("Error updating IP address:", error.message); } } async AddIpisBlocked(ip) { try { const collection = this.collection("FastJsAPI"); const filter = { ip: ip }; const update = { $set: { blocked: true } }; const result = await collection.updateOne(filter, update, { upsert: true }); if (result.upsertedCount > 0) { console.log("Inserted IP address blocked:", ip); } else { console.log("Updated an existing IP address:", ip); } } catch (error) { console.error("Error updating IP address:", error.message); } } async CheckIsBlocked(ip) { try { const collection = this.collection("FastJsAPI"); const filter = { ip: ip }; const update = { $set: { blocked: true } }; const FindIp = await collection.findOne(filter); if (FindIp) { return FindIp; } else { console.log("IP not found in the database"); return null } } catch (error) { console.error("Error checking IP:", error.message); return null } } }; export { Database };