first commit
This commit is contained in:
60
config/database.js
Normal file
60
config/database.js
Normal file
@@ -0,0 +1,60 @@
|
||||
import mongoose from "mongoose";
|
||||
import { config } from "./index.js";
|
||||
|
||||
let isConnected = false;
|
||||
|
||||
export const connectDatabase = async () => {
|
||||
if (isConnected) {
|
||||
console.log("📦 Using existing database connection");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const options = {
|
||||
maxPoolSize: 10,
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
socketTimeoutMS: 45000,
|
||||
};
|
||||
|
||||
await mongoose.connect(config.mongodb.uri, options);
|
||||
|
||||
isConnected = true;
|
||||
|
||||
console.log("✅ MongoDB connected successfully");
|
||||
|
||||
mongoose.connection.on("error", (err) => {
|
||||
console.error("❌ MongoDB connection error:", err);
|
||||
isConnected = false;
|
||||
});
|
||||
|
||||
mongoose.connection.on("disconnected", () => {
|
||||
console.warn("⚠️ MongoDB disconnected");
|
||||
isConnected = false;
|
||||
});
|
||||
|
||||
process.on("SIGINT", async () => {
|
||||
await mongoose.connection.close();
|
||||
console.log("🔌 MongoDB connection closed through app termination");
|
||||
process.exit(0);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("❌ Error connecting to MongoDB:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
export const disconnectDatabase = async () => {
|
||||
if (!isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await mongoose.connection.close();
|
||||
isConnected = false;
|
||||
console.log("🔌 MongoDB disconnected");
|
||||
} catch (error) {
|
||||
console.error("❌ Error disconnecting from MongoDB:", error);
|
||||
}
|
||||
};
|
||||
|
||||
export default { connectDatabase, disconnectDatabase };
|
||||
Reference in New Issue
Block a user