From aa220f394f123ba8780f46298d6ba0e8bdfecd7c Mon Sep 17 00:00:00 2001 From: Alvaro Vega Date: Tue, 10 Dec 2024 17:58:03 +0100 Subject: [PATCH] add missed callback to db init --- lib/model/dbConn.js | 95 ++++++++++++++++++++++++++++++--------------- 1 file changed, 64 insertions(+), 31 deletions(-) diff --git a/lib/model/dbConn.js b/lib/model/dbConn.js index 66fc71f..99c696a 100644 --- a/lib/model/dbConn.js +++ b/lib/model/dbConn.js @@ -31,6 +31,7 @@ const config = require('../utils/commonConfig'); const constants = require('../utils/constants'); const errors = require('../errors'); const DEFAULT_DB_NAME = 'iotagent-manager'; +//let defaultDb; mongoose.Promise = global.Promise; // not including this causes DeprecationWarning @@ -49,8 +50,10 @@ function delay(ms) { * * @this Reference to the dbConn module itself. */ -async function init(logger, host, db, port, username, password, options) { +function init(logger, host, db, port, username, password, options, callback) { let credentials = ''; + let retries = 0; + let lastError; if (username && password) { credentials = `${username}:${password}@`; } @@ -67,38 +70,66 @@ async function init(logger, host, db, port, username, password, options) { const maxRetries = config.getConfig().mongodb?.retries || constants.DEFAULT_MONGODB_RETRIES; const retryTime = config.getConfig().mongodb?.retryTime || constants.DEFAULT_MONGODB_RETRY_TIME; - /* eslint-disable no-await-in-loop */ - for (let attempt = 1; attempt <= maxRetries; attempt++) { - try { - logger.info(`Attempt ${attempt}: Connecting to MongoDB at ${url}`); - await mongoose.connect(url, options); - logger.info('Successfully connected to MongoDB.'); - - // Register events - mongoose.connection.on('error', (err) => logger.error('Mongo Driver error:', err)); - mongoose.connection.on('connected', () => logger.debug('Mongo Driver connected')); - mongoose.connection.on('disconnected', () => logger.debug('Mongo Driver disconnected')); - mongoose.connection.on('reconnectFailed', () => { - logger.error('MONGODB-004: MongoDB connection was lost'); - process.exit(1); - }); + // /* eslint-disable no-await-in-loop */ + // for (let attempt = 1; attempt <= maxRetries; attempt++) { + // try { + // logger.info(`Attempt ${attempt}: Connecting to MongoDB at ${url}`); + // mongoose.connect(url, options); + // //logger.info('Successfully connected to MongoDB.'); + + // // Register events + // mongoose.connection.on('error', (err) => logger.error('Mongo Driver error:', err)); + // mongoose.connection.on('connected', () => logger.debug('Mongo Driver connected')); + // mongoose.connection.on('disconnected', () => logger.debug('Mongo Driver disconnected')); + // mongoose.connection.on('reconnectFailed', () => { + // logger.error('MONGODB-004: MongoDB connection was lost'); + // process.exit(1); + // }); + // //module.exports.db = defaultDb; + // loadModels(); + // break; // End loop if connection was OK + // } catch (error) { + // logger.error(`Attempt ${attempt} failed: ${error}`); + // if (attempt < maxRetries) { + // logger.info(`Retrying in ${retryTime} seconds...`); + // delay(retryTime * 1000); + // } else { + // throw new Error(`MONGODB-002: Connection failed after ${maxRetries} attempts.`); + // } + // } + // } + // /* eslint-enable no-await-in-loop */ + function connectionAttempt(callback) { + logger.info(context, `Attempting to connect to MongoDB at ${url}. Attempt ${retries + 1}`); - loadModels(); - break; // End loop if connection was OK - } catch (error) { - logger.error(`Attempt ${attempt} failed: ${error}`); - if (attempt < maxRetries) { - logger.info(`Retrying in ${retryTime} seconds...`); - await delay(retryTime * 1000); - } else { - throw new Error(`MONGODB-002: Connection failed after ${maxRetries} attempts.`); - } - } + mongoose + .connect(url, options) + .then(() => { + //defaultDb = connection.connection; + defaultDb = mongoose.connection; + logger.info(context, 'Successfully connected to MongoDB.'); + loadModels(); + callback(); + }) + .catch((err) => { + logger.error(context, `MONGODB-001: Error trying to connect to MongoDB: ${err}`); + //lastError = err; + retries++; + if (retries < maxRetries) { + //const retryTime = config.getConfig().mongodb?.retryTime || constants.DEFAULT_MONGODB_RETRY_TIME; + logger.info(context, `Retrying in ${retryTime} seconds...`); + setTimeout(() => connectionAttempt(callback), retryTime * 1000); + } else { + logger.error(context, `MONGODB-002: Failed to connect after ${maxRetries} attempts.`); + callback(err); + } + }); } - /* eslint-enable no-await-in-loop */ + + connectionAttempt(callback); } -async function configureDb(logger) { +function configureDb(logger, callback) { const currentConfig = config.getConfig(); if (!currentConfig.mongodb?.host) { logger.fatal('No host found for MongoDB driver.'); @@ -109,16 +140,18 @@ async function configureDb(logger) { const port = currentConfig.mongodb.port || 27017; const options = currentConfig.mongodb.replicaSet ? { replicaSet: currentConfig.mongodb.replicaSet } : {}; - await init( + init( logger, currentConfig.mongodb.host, dbName, port, currentConfig.username, currentConfig.password, - options + options, + callback ); } exports.configureDb = configureDb; +//exports.db = defaultDb; exports.DEFAULT_DB_NAME = DEFAULT_DB_NAME;