From 6a811c708b7a771e8bc2e0761ab4efef81975abe Mon Sep 17 00:00:00 2001 From: Ruben Talstra Date: Sun, 15 Jun 2025 12:04:55 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20refactor:=20Move=20MongoDB=20con?= =?UTF-8?q?nection=20logic=20to=20a=20separate=20module=20and=20make=20dat?= =?UTF-8?q?abase=20name=20optional?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/lib/db/connect.js | 53 +++++++++++++++++++++++++++++++++++++++++ api/lib/db/connectDb.js | 5 ---- 2 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 api/lib/db/connect.js diff --git a/api/lib/db/connect.js b/api/lib/db/connect.js new file mode 100644 index 0000000000..706f67cc07 --- /dev/null +++ b/api/lib/db/connect.js @@ -0,0 +1,53 @@ +require('dotenv').config(); +const mongoose = require('mongoose'); +const MONGO_URI = process.env.MONGO_URI; +const MONGO_DB_NAME = process.env.MONGO_DB_NAME; + +if (!MONGO_URI) { + throw new Error('Please define the MONGO_URI environment variable'); +} + +/** + * Global is used here to maintain a cached connection across hot reloads + * in development. This prevents connections growing exponentially + * during API Route usage. + */ +let cached = global.mongoose; + +if (!cached) { + cached = global.mongoose = { conn: null, promise: null }; +} + +async function connectDb() { + if (cached.conn && cached.conn?._readyState === 1) { + return cached.conn; + } + + const disconnected = cached.conn && cached.conn?._readyState !== 1; + if (!cached.promise || disconnected) { + const opts = { + bufferCommands: false, + // useNewUrlParser: true, + // useUnifiedTopology: true, + // bufferMaxEntries: 0, + // useFindAndModify: true, + // useCreateIndex: true + }; + + if (MONGO_DB_NAME) { + opts.dbName = MONGO_DB_NAME; + } + + mongoose.set('strictQuery', true); + cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { + return mongoose; + }); + } + cached.conn = await cached.promise; + + return cached.conn; +} + +module.exports = { + connectDb, +}; diff --git a/api/lib/db/connectDb.js b/api/lib/db/connectDb.js index c6a34c6fdd..b8cbeb2adb 100644 --- a/api/lib/db/connectDb.js +++ b/api/lib/db/connectDb.js @@ -1,7 +1,6 @@ require('dotenv').config(); const mongoose = require('mongoose'); const MONGO_URI = process.env.MONGO_URI; -const MONGO_DB_NAME = process.env.MONGO_DB_NAME; if (!MONGO_URI) { throw new Error('Please define the MONGO_URI environment variable'); @@ -34,10 +33,6 @@ async function connectDb() { // useCreateIndex: true }; - if (MONGO_DB_NAME) { - opts.dbName = MONGO_DB_NAME; - } - mongoose.set('strictQuery', true); cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { return mongoose;