auth-service / src /config /database.ts
seraj-b2
Initial commit of Google Auth Backend Service
b480ef7
Raw History Blame Contribute Delete
1.15 kB
import mongoose from 'mongoose';
import { env } from './env';
import { logger } from '../utils/logger';
export const connectDatabase = async (uri: string = env.MONGO_URI): Promise<typeof mongoose> => {
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<void> => {
if (mongoose.connection.readyState !== 0) {
await mongoose.disconnect();
logger.info('MongoDB connection closed.');
}
};
export const isDatabaseConnected = (): boolean => {
return mongoose.connection.readyState === 1;
};