From ab03900adf080da08a0b2a3628fd0dcf0af28420 Mon Sep 17 00:00:00 2001 From: schererleander Date: Wed, 2 Jul 2025 22:17:57 +0200 Subject: feat: add libraries and utilities --- src/lib/mongodb.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/lib/mongodb.ts (limited to 'src/lib/mongodb.ts') diff --git a/src/lib/mongodb.ts b/src/lib/mongodb.ts new file mode 100644 index 0000000..1fc60d4 --- /dev/null +++ b/src/lib/mongodb.ts @@ -0,0 +1,30 @@ +import mongoose from "mongoose"; + +const MONGODB_URI = process.env.MONGODB_URI; + +if (!MONGODB_URI) { + throw new Error("Please define the MONGODB_URI environment variable inside .env.local"); +} + +interface Connection { + isConnected?: number; +} + +const connection: Connection = {}; + +async function dbConnect(): Promise { + if (connection.isConnected) { + return; + } + + try { + const db = await mongoose.connect(MONGODB_URI!); + connection.isConnected = db.connections[0].readyState; + console.log("MongoDB connected successfully"); + } catch (error) { + console.error("MongoDB connection error:", error); + throw error; + } +} + +export default dbConnect; \ No newline at end of file -- cgit v1.3.1