CoolFace
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
database.js126 linesDownload Raw Back to utils
1/**2 * Database Utilities3 * Helper functions for database operations4 */5 6const mongoose = require('mongoose');7const logger = require('./logger');8const { config } = require('../config/env.config');9 10/**11 * Connect to MongoDB with retry logic12 */13const connectDB = async (retries = 5) => {14  const options = {15    serverSelectionTimeoutMS: 10000,16    socketTimeoutMS: 60000,17    family: 4, // Use IPv418    maxPoolSize: 100,19    minPoolSize: 20,20    maxIdleTimeMS: 30000,21  };22 23  for (let i = 0; i < retries; i++) {24    try {25      logger.info(`Attempting to connect to MongoDB (attempt ${i + 1}/${retries})...`);26      await mongoose.connect(config.mongodb.uri, options);27      logger.success('MongoDB connected successfully');28      return;29    } catch (error) {30      logger.error(`MongoDB connection attempt ${i + 1} failed`, error);31      32      if (i === retries - 1) {33        logger.error('All MongoDB connection attempts failed');34        throw error;35      }36      37      // Wait before retrying (exponential backoff)38      const waitTime = Math.min(1000 * Math.pow(2, i), 10000);39      logger.info(`Retrying in ${waitTime}ms...`);40      await new Promise(resolve => setTimeout(resolve, waitTime));41    }42  }43};44 45/**46 * Gracefully close database connection47 */48const disconnectDB = async () => {49  try {50    await mongoose.connection.close();51    logger.info('MongoDB connection closed');52  } catch (error) {53    logger.error('Error closing MongoDB connection', error);54    throw error;55  }56};57 58/**59 * Check if database is connected60 */61const isConnected = () => {62  return mongoose.connection.readyState === 1;63};64 65/**66 * Get database connection stats67 */68const getConnectionStats = () => {69  const state = mongoose.connection.readyState;70  const states = {71    0: 'disconnected',72    1: 'connected',73    2: 'connecting',74    3: 'disconnecting',75  };76 77  return {78    state: states[state] || 'unknown',79    host: mongoose.connection.host,80    port: mongoose.connection.port,81    name: mongoose.connection.name,82  };83};84 85/**86 * Setup database event listeners87 */88const setupEventListeners = () => {89  mongoose.connection.on('connected', () => {90    logger.success('MongoDB connected');91  });92 93  mongoose.connection.on('error', (err) => {94    logger.error('MongoDB connection error', err);95  });96 97  mongoose.connection.on('disconnected', () => {98    logger.warn('MongoDB disconnected');99  });100 101  mongoose.connection.on('reconnected', () => {102    logger.success('MongoDB reconnected');103  });104 105  // Handle process termination106  process.on('SIGINT', async () => {107    await disconnectDB();108    logger.info('MongoDB connection closed due to app termination');109    process.exit(0);110  });111 112  process.on('SIGTERM', async () => {113    await disconnectDB();114    logger.info('MongoDB connection closed due to app termination');115    process.exit(0);116  });117};118 119module.exports = {120  connectDB,121  disconnectDB,122  isConnected,123  getConnectionStats,124  setupEventListeners,125};126