1

I am working on an api where response time of api is very important (in the context of this answer: https://stackoverflow.com/a/60910024/4378475) I have two database initializations, mongodb and firebase, I want to calculate exactly how much time it takes to connect these databases

here is my code:

const dbURI = `mongodb://xxxxxxxxxxxxxxxx`
let timeCounter = 0;

export function initMongoDb() {

    timeCounter = Date.now();

    if (mongoose.connection.readyState !== mongoose.STATES.connected
        && mongoose.connection.readyState !== mongoose.STATES.connecting) {

        console.log("initializing mongoose");

        mongoose.connect(dbURI, {
            useNewUrlParser: true, useUnifiedTopology: true
        }).catch(e => {
            console.log("mongo connection failed for reason: ", e);
        })
    } else {
        console.log("mongoose already connected: ", mongoose.STATES[mongoose.connection.readyState], "took: ", Date.now() - timeCounter, "ms");
    }
}

mongoose.connection.on('connected', function () {//connected
    console.log("mongooseListner: Mongoose is connected, took: ", Date.now() - timeCounter,"ms");
});

which gives me log like this:

> mongooseListner: Mongoose is connected, took: 1310 ms

or

> mongoose already connected: connected took: 0 ms

I want same thing for firebase database, here is my code:


export function initFirebase(){
    if (admin.apps.length === 0) {
        console.log("initializing firebase database");
        admin.initializeApp(functions.config().firebase)
    }else{
        console.log("firebase is already initialized");
    }
}

but firebase initializeApp method does not provide(best of my knowledge and docs I have gone through so far) any promise or connected event so I am unable to calculate how much time does it actually takes to initialize

please suggest how can I do that, any workaround anything would be appriciated

Inzamam Malik
  • 3,238
  • 3
  • 29
  • 61

1 Answers1

1

Initialization of the FirebaseApp instance is synchronous. So when the initializeApp call returns, it is done.

timeCounter = Date.now();
initFirebase();
console.log("Initializing Firebase took: ", Date.now() - timeCounter,"ms");

Note however that this simply initializes some local variables, while the Mongoose code seems to actually connect to the database. The connection between the Firebase client and the Firestore backend is connectionless, so there isn't a real equivalent to what you're doing for Mongoose. The closest you can probably get is logging how long the first write or read operation takes.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807