Forráskód Böngészése

RHL-005-refactor(db): refactor MongoDB connection to use Mongoose and improve error handling

Code_Uwe 1 napja
szülő
commit
60920aeffe
1 módosított fájl, 35 hozzáadás és 15 törlés
  1. 35 15
      lib/db.js

+ 35 - 15
lib/db.js

@@ -1,28 +1,48 @@
 // lib/db.js
-import { MongoClient } from "mongodb";
+import mongoose from "mongoose";
 
-const uri = process.env.MONGODB_URI;
+// Reuse the connection across hot reloads in dev and across route handler invocations.
+const globalForMongoose = globalThis;
 
-let client;
-let clientPromise;
+const cached =
+	globalForMongoose.__mongooseCache ||
+	(globalForMongoose.__mongooseCache = { conn: null, promise: null });
+
+async function connectMongoose() {
+	const uri = process.env.MONGODB_URI;
 
-function getClientPromise() {
 	if (!uri) {
-		// Jetzt meckern wir erst beim tatsächlichen Zugriff auf die DB
-		throw new Error("MONGODB_URI ist nicht gesetzt (Env prüfen)");
+		throw new Error("MONGODB_URI environment variable is not set");
+	}
+
+	if (cached.conn) {
+		return cached.conn;
 	}
 
-	if (!clientPromise) {
-		// In Dev-Umgebungen könnte man global._mongoClientPromise nutzen;
-		// auf dem Server reicht ein einfacher Singleton.
-		client = new MongoClient(uri);
-		clientPromise = client.connect();
+	if (!cached.promise) {
+		cached.promise = mongoose
+			.connect(uri, {
+				// Fail fast if someone queries before we are connected
+				bufferCommands: false,
+			})
+			.then((m) => m);
 	}
 
-	return clientPromise;
+	cached.conn = await cached.promise;
+	return cached.conn;
 }
 
+/**
+ * Returns the native MongoDB db handle (from the active Mongoose connection).
+ * This also ensures the Mongoose connection is established.
+ */
 export async function getDb() {
-	const client = await getClientPromise();
-	return client.db();
+	await connectMongoose();
+
+	const db = mongoose.connection?.db;
+	if (!db) {
+		throw new Error("MongoDB connection is not ready");
+	}
+
+	return db;
 }