huge changes
This commit is contained in:
@@ -25,14 +25,20 @@ async function connectMongoDB(uri, options = {}) {
|
||||
// Handle connection events
|
||||
mongoose.connection.on('error', (err) => {
|
||||
console.error('MongoDB connection error:', err);
|
||||
const { logSystem: ls } = require('./services/debugLog');
|
||||
ls('MongoDB error', [{ name: 'Error', value: err.message }], null, 0xFF0000).catch(() => {});
|
||||
});
|
||||
|
||||
mongoose.connection.on('disconnected', () => {
|
||||
console.warn('MongoDB disconnected. Attempting to reconnect...');
|
||||
const { logSystem: ls } = require('./services/debugLog');
|
||||
ls('MongoDB disconnected', [], null, 0xFFFF00).catch(() => {});
|
||||
});
|
||||
|
||||
mongoose.connection.on('reconnected', () => {
|
||||
console.log('✓ MongoDB reconnected');
|
||||
const { logSystem: ls } = require('./services/debugLog');
|
||||
ls('MongoDB reconnected', []).catch(() => {});
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
@@ -55,8 +61,32 @@ async function closeMongoDB() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry a function on Mongoose connection errors.
|
||||
* @param {Function} fn - async function to execute
|
||||
* @param {object} options - { retries: 3, delayMs: 500 }
|
||||
* @returns {Promise<*>}
|
||||
*/
|
||||
async function withRetry(fn, options = {}) {
|
||||
const { retries = 3, delayMs = 500 } = options;
|
||||
let lastError;
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
const isConnectionError = err.name === 'MongoNetworkError' ||
|
||||
mongoose.connection.readyState !== 1;
|
||||
if (!isConnectionError || attempt >= retries) throw err;
|
||||
await new Promise(r => setTimeout(r, delayMs));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
connectMongoDB,
|
||||
closeMongoDB,
|
||||
withRetry,
|
||||
mongoose
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user