File size: 3,072 Bytes
167ec72 626485b 167ec72 effc4d3 81e7811 effc4d3 81e7811 c8506c4 81e7811 c8506c4 81e7811 167ec72 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
import { MongoClient } from 'mongodb';
import * as config from './config.js';
if (!config.dbUri) {
throw new Error("Missing DB_URI environment variable");
}
const client = new MongoClient(config.dbUri);
class Database {
constructor(dbname, collectionName) {
this.dbname = dbname;
this.collectionName = collectionName;
}
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() {
try {
const db = client.db(this.dbname);
return db.collection(this.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(); // Access collection
const filter = { ip: ip }; // Filter to find the IP
const update = { $set: { ip: ip } }; // Update IP field
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 AddIpisBlocked(ip) {
try {
const collection = this.collection();
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 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 CheckIsBlocked(ip) {
try {
const collection = this.collection();
const filter = { ip: ip };
const update = { $set: { blocked: true } };
const FindIp = await collection.findOne(filter);
if (FindIp) {
console.log("IP found in the database:", 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 }; |