@@ -3,51 +3,43 @@ import {ObjectId} from "mongodb";
33import dotenv from "dotenv" ;
44dotenv . config ( ) ;
55
6- import LOGGER from "../utils/logger.js" ;
76import Constants from "../constants/dbConstants.js" ;
7+ import LOGGER from "../utils/logger.js" ;
88
99const { CORE_DB } = Constants ;
1010
11- const buildMongoUri = ( ) => {
12- const user = process . env . MONGO_USER ;
13- const password = process . env . MONGO_PASS ;
14- const clusterName = process . env . MONGO_CLUSTER ;
15- const domainName = process . env . MONGO_DOMAIN ;
16- if ( ! user ) {
17- return LOGGER . error ( `Invalid admin user found while building mongo uri` ) ;
18- }
19- if ( ! password ) {
20- return LOGGER . error (
21- `Invalid admin password found while building mongo uri`
22- ) ;
23- }
24- if ( ! clusterName ) {
25- return LOGGER . error ( `Invalid cluster name found while building mongo uri` ) ;
11+ /* Database Connections */
12+ const client = new MongoClient ( process . env . MONGO_URI ) ;
13+ let isConnected = false ;
14+
15+ export const connectToDb = async ( ) => {
16+ if ( isConnected ) {
17+ return client ; // reuse existing connection
2618 }
27- if ( ! domainName ) {
28- return LOGGER . error ( `Invalid domain name found while building mongo uri` ) ;
19+ try {
20+ await client . connect ( ) ;
21+ isConnected = true ;
22+ LOGGER . info ( "✅ Connected to MongoDB" ) ;
23+ return client ;
24+ } catch ( err ) {
25+ LOGGER . error ( "❌ Failed to connect to MongoDB" , err ) ;
26+ throw err ;
2927 }
30- return `mongodb+srv://${ user } :${ password } @${ clusterName } .${ domainName } ?retryWrites=true&w=majority` ;
3128} ;
3229
33- const client = new MongoClient ( buildMongoUri ( ) ) ;
34-
35- /* Database Connections */
3630export const performAdminAction = async ( action , username ) => {
3731 try {
38- await client . connect ( ) ;
32+ await connectToDb ( ) ;
3933 return await action ( client , CORE_DB , "Admin" , username ) ;
4034 } catch ( err ) {
4135 console . error ( err ) ;
4236 return err ;
43- } finally {
44- await client . close ( ) ;
4537 }
4638} ;
4739
4840export const performDBAction = async ( action , dbName , collection , id , qps ) => {
4941 try {
50- await client . connect ( ) ;
42+ await connectToDb ( ) ;
5143 const queryActions = [ getSortQuery ( qps ) , getLimitSize ( qps ) ] ;
5244 return await action (
5345 client ,
@@ -60,20 +52,16 @@ export const performDBAction = async (action, dbName, collection, id, qps) => {
6052 } catch ( err ) {
6153 console . error ( err ) ;
6254 return err ;
63- } finally {
64- await client . close ( ) ;
6555 }
6656} ;
6757
6858export const listCollections = async ( dbName ) => {
6959 try {
70- await client . connect ( ) ;
60+ await connectToDb ( ) ;
7161 return await client . db ( dbName ) . listCollections ( ) . toArray ( ) ;
7262 } catch ( err ) {
7363 console . error ( err ) ;
7464 return err ;
75- } finally {
76- await client . close ( ) ;
7765 }
7866} ;
7967
0 commit comments