Last active
February 1, 2024 13:06
-
-
Save Talhafayyaz11/f3428bb96f35768007230708422f7608 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MongoClient = require('mongodb').MongoClient; | |
var DbConnection = function () { | |
var db = null; | |
var instance = 0; | |
async function DbConnect() { | |
try { | |
let url = 'mongodb://myurl.blablabla'; | |
let _db = await MongoClient.connect(url); | |
return _db | |
} catch (e) { | |
return e; | |
} | |
} | |
async function Get() { | |
try { | |
instance++; // this is just to count how many times our singleton is called. | |
console.log(`DbConnection called ${instance} times`); | |
if (db != null) { | |
console.log(`db connection is already alive`); | |
return db; | |
} else { | |
console.log(`getting new db connection`); | |
db = await DbConnect(); | |
return db; | |
} | |
} catch (e) { | |
return e; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment