import mongoose from 'mongoose'; import { env } from './env'; import { logger } from '../utils/logger'; export const connectDatabase = async (uri: string = env.MONGO_URI): Promise => { try { mongoose.set('strictQuery', true); const connection = await mongoose.connect(uri, { serverSelectionTimeoutMS: 10000, socketTimeoutMS: 45000 }); logger.info(`📦 MongoDB connected successfully to database: "${mongoose.connection.name}"`); mongoose.connection.on('error', (err) => { logger.error('MongoDB connection error:', err); }); mongoose.connection.on('disconnected', () => { logger.warn('MongoDB disconnected. Attempting to reconnect...'); }); return connection; } catch (error) { logger.error('Failed to connect to MongoDB:', error); throw error; } }; export const disconnectDatabase = async (): Promise => { if (mongoose.connection.readyState !== 0) { await mongoose.disconnect(); logger.info('MongoDB connection closed.'); } }; export const isDatabaseConnected = (): boolean => { return mongoose.connection.readyState === 1; };