|
1 | | -// dbConfig.ts - establish a connection to a MongoDB database |
2 | | -import mongoose from 'mongoose'; |
| 1 | +// dbConfig.ts |
| 2 | +import mongoose from "mongoose"; |
3 | 3 |
|
4 | | -export async function connect() { |
5 | | - try { |
6 | | - if (!process.env.MONGO_DB_URL) { |
7 | | - throw new Error("MONGO_DB_URL is not defined. Check your environment variables."); |
8 | | - } |
| 4 | +let isConnected = false; // track connection status |
9 | 5 |
|
10 | | - await mongoose.connect(process.env.MONGO_DB_URL, { |
11 | | - } as mongoose.ConnectOptions); |
| 6 | +export async function connect() { |
| 7 | + if (isConnected) return; // singleton pattern |
12 | 8 |
|
13 | | - const connection = mongoose.connection; |
| 9 | + const uri = process.env.MONGO_DB_URL; |
| 10 | + if (!uri) throw new Error("MONGO_DB_URL is not defined"); |
14 | 11 |
|
15 | | - connection.on('connected', () => { |
16 | | - console.log("MongoDB connected successfully"); |
17 | | - }); |
| 12 | + try { |
| 13 | + await mongoose.connect(uri); |
| 14 | + console.log("MongoDB connected"); |
| 15 | + isConnected = true; |
| 16 | + } catch (err) { |
| 17 | + console.error("MongoDB connection error:", err); |
| 18 | + throw err; |
| 19 | + } |
| 20 | +} |
18 | 21 |
|
19 | | - connection.on('error', (err) => { |
20 | | - console.error("MongoDB connection error:", err); |
21 | | - process.exit(1); |
22 | | - }); |
23 | | - } catch (error) { |
24 | | - console.error("MongoDB connection failed:", error); |
25 | | - process.exit(1); |
26 | | - } |
| 22 | +export async function disconnect() { |
| 23 | + if (!isConnected) return; |
| 24 | + await mongoose.disconnect(); |
| 25 | + isConnected = false; |
27 | 26 | } |
0 commit comments