I built a TS, MongoDB Client wrapper. for some reason when I call the function that gets the connection, its callback is called twice.
There are 2 calls in total to the get() function, 1 before the export as you can see and another from a mocha test.
I am pretty new to TS and JS in general, but this seems a bit off.
import {Db, MongoClient} from "mongodb"; import {MongoConfig} from '../config/config' class DbClient { private cachedDb : Db = null; private async connectToDatabase() { console.log('=> connect to database'); let connectionString : string = "mongodb://" + MongoConfig.host + ":" + MongoConfig.port; return MongoClient.connect(connectionString) .then(db => { console.log('=> connected to database'); this.cachedDb = db.db(MongoConfig.database); return this.cachedDb; }); } public async get() { if (this.cachedDb) { console.log('=> using cached database instance'); return Promise.resolve(this.cachedDb); }else{ return this.connectToDatabase(); } } } let client = new DbClient(); client.get(); export = client;
where the console output is:
=> connect to database => connected to database => connected to database
Any particular reason this is misbehaving?