Fix a bug in db connections

Fix a bug caused by concurrent calls to obtain db clients.
This commit is contained in:
Shweelan Samson authored and Zaid Abdulla committed 2018-12-26 00:22:07 -08:00
1 parent afa2e6d928
commit 8b5cd384ab
1 file changed
+29 -18
+29 -18
View File
@@ -5,7 +5,7 @@ const config = require("./config");
const mongodbFunctions = require("./mongodb-functions"); const mongodbFunctions = require("./mongodb-functions");
const expression = require("../common/expression"); const expression = require("../common/expression");
const _client = {}; let _clientPromise = null;
const RESOURCE_DB = { const RESOURCE_DB = {
devices: "genieacs", devices: "genieacs",
@@ -16,20 +16,21 @@ const RESOURCE_DB = {
files: "genieacs" files: "genieacs"
}; };
function getClient(db) { function getClient() {
if (_client[db]) return Promise.resolve(_client[db]); if (!_clientPromise)
_clientPromise = new Promise((resolve, reject) => {
const CONNECTION_URL = config.server.mongodbConnectionUrl;
mongodb.MongoClient.connect(
CONNECTION_URL,
{ useNewUrlParser: true },
(err, client) => {
if (err) return reject(err);
resolve(client);
}
);
});
return new Promise((resolve, reject) => { return _clientPromise;
const CONNECTION_URL = config.server.mongodbConnectionUrl;
mongodb.MongoClient.connect(
CONNECTION_URL,
{ useNewUrlParser: true },
(err, client) => {
if (err) return reject(err);
resolve((_client[db] = client.db(db)));
}
);
});
} }
function query(resource, filter, options, callback) { function query(resource, filter, options, callback) {
@@ -50,8 +51,10 @@ function query(resource, filter, options, callback) {
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
getClient(RESOURCE_DB[resource]).then(client => { getClient().then(client => {
const collection = client.collection(resource); const collection = client
.db(RESOURCE_DB[resource])
.collection(resource);
let cursor = collection.find( let cursor = collection.find(
q, q,
resource === "Devices" resource === "Devices"
@@ -126,8 +129,8 @@ function count(resource, filter) {
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
getClient(RESOURCE_DB[resource]).then(client => { getClient().then(client => {
const collection = client.collection(resource); const collection = client.db(RESOURCE_DB[resource]).collection(resource);
collection.find(q).count((err, c) => { collection.find(q).count((err, c) => {
if (err) reject(err); if (err) reject(err);
else resolve(c); else resolve(c);
@@ -136,5 +139,13 @@ function count(resource, filter) {
}); });
} }
function disconnect() {
if (_clientPromise)
_clientPromise.then(client => {
client.close();
});
}
exports.query = query; exports.query = query;
exports.count = count; exports.count = count;
exports.disconnect = disconnect;