Skip to content

Commit

Permalink
Merge pull request #40 from Shu12388y/main
Browse files Browse the repository at this point in the history
resolve the database connection
  • Loading branch information
Shu12388y authored Oct 11, 2024
2 parents 7653606 + f3f799c commit ae3cf72
Showing 1 changed file with 12 additions and 38 deletions.
50 changes: 12 additions & 38 deletions src/db/dbConnect.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,15 @@
import mongoose from "mongoose";

const MONGODB_URI = process.env.MONGO_URI;

if (!MONGODB_URI) {
throw new Error('Please define the MONGO_URI environment variable inside .env.local');
}

let cached = global.mongoose;

if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}

export async function dbConnect() {
if (cached.conn) {
console.log("Using cached database connection.");
return cached.conn;
try {
mongoose.connect(process.env.MONGO_URI!);
const connection = mongoose.connection;
connection.on("connected", () => {
console.log("Database connected");
});
connection.on("error", (err) => {
console.log("error: ", err);
});
} catch (error: any) {
console.log(error);
}

if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
bufferCommands: false,
};

cached.promise = mongoose.connect(MONGODB_URI, opts)
.then((mongooseInstance) => {
console.log("Database connected successfully.");
return mongooseInstance;
})
.catch((err) => {
console.error("Database connection error: ", err);
throw new Error(`Database connection failed: ${err.message}`);
});
}

cached.conn = await cached.promise;
return cached.conn;
}
}

0 comments on commit ae3cf72

Please sign in to comment.