Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import mongoose from "mongoose"; if (!process.env.MONGODB_URI) { throw new Error('Invalid/Missing environment variable: "MONGODB_URI"'); } const MONGODB_URI = process.env.MONGODB_URI; interface MongooseCache { conn: typeof mongoose | null; promise: Promise<typeof mongoose> | null; } declare global { var mongoose: MongooseCache | undefined; } const cached: MongooseCache = global.mongoose || { conn: null, promise: null }; if (!global.mongoose) { global.mongoose = cached; } export async function connectDB(): Promise<typeof mongoose> { if (cached.conn) { return cached.conn; } if (!cached.promise) { const opts = { bufferCommands: false, }; cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { console.log("✅ MongoDB connected successfully"); return mongoose; }); } try { cached.conn = await cached.promise; } catch (e) { cached.promise = null; console.error("❌ MongoDB connection error:", e); throw e; } return cached.conn; } export default connectDB; |