Skip to content

Commit

Permalink
add missed callback to db init
Browse files Browse the repository at this point in the history
  • Loading branch information
AlvaroVega committed Dec 10, 2024
1 parent 8964e4b commit aa220f3
Showing 1 changed file with 64 additions and 31 deletions.
95 changes: 64 additions & 31 deletions lib/model/dbConn.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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;

Check failure on line 56 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'lastError' is defined but never used
if (username && password) {
credentials = `${username}:${password}@`;
}
Expand All @@ -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}`);

Check failure on line 103 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'context' is not defined

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;

Check failure on line 109 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'defaultDb' is not defined
logger.info(context, 'Successfully connected to MongoDB.');

Check failure on line 110 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'context' is not defined
loadModels();
callback();
})
.catch((err) => {
logger.error(context, `MONGODB-001: Error trying to connect to MongoDB: ${err}`);

Check failure on line 115 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'context' is not defined
//lastError = err;
retries++;
if (retries < maxRetries) {
//const retryTime = config.getConfig().mongodb?.retryTime || constants.DEFAULT_MONGODB_RETRY_TIME;
logger.info(context, `Retrying in ${retryTime} seconds...`);

Check failure on line 120 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'context' is not defined
setTimeout(() => connectionAttempt(callback), retryTime * 1000);
} else {
logger.error(context, `MONGODB-002: Failed to connect after ${maxRetries} attempts.`);

Check failure on line 123 in lib/model/dbConn.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript

'context' is not defined
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.');
Expand All @@ -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;

0 comments on commit aa220f3

Please sign in to comment.