The following piece of code may potentially crash the server during startup if the Mongo connection takes longer and it will manage to make a first request to the DB (while db is still empty).
|
db = client.db(process.env.DB_NAME); |
I'd recommend wrapping the connection piece in a Promise which will be resolved upon successful connection and wait for the promise during the initialization so you'll be sure that the db connection is present when making the first request.
const initMongo = () => new Promise((resolve, reject) => {
MongoClient.connect(process.env.DB_URL, async (err, client) => {
assert.equal(null, err);
console.log('Database connection was successful.');
db = client.db(process.env.DB_NAME);
resolve(); // you could also resolve the `db` to use it in other layers
});
});
module.exports = {
initMongo,
...
and then in the ws.js:
initMongo().then(() => {
server.listen(...)
});
Of course use async/await if you want. That's just a one way of doing it.
The following piece of code may potentially crash the server during startup if the Mongo connection takes longer and it will manage to make a first request to the DB (while
dbis still empty).SimpleAlerts/SimpleAlerts-Server/database/db.js
Line 11 in d876a62
I'd recommend wrapping the connection piece in a Promise which will be resolved upon successful connection and wait for the promise during the initialization so you'll be sure that the db connection is present when making the first request.
and then in the
ws.js:Of course use async/await if you want. That's just a one way of doing it.