ai-wpa/lib/mongodb.ts

88 lines
2.4 KiB
TypeScript

import mongoose from 'mongoose'
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/siliconpin'
if (!MONGODB_URI) {
throw new Error('Please define the MONGODB_URI environment variable inside .env.local')
}
interface CachedConnection {
conn: typeof mongoose | null
promise: Promise<typeof mongoose> | null
}
// Global variable to cache the database connection across hot reloads in development
declare global {
var mongoose: CachedConnection | undefined
}
let cached: CachedConnection = global.mongoose || { conn: null, promise: null }
if (!global.mongoose) {
global.mongoose = cached
}
async function connectDB(): Promise<typeof mongoose> {
// Skip database connection during build phase
const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build'
if (isBuildTime) {
throw new Error('Database connection skipped during build phase')
}
if (cached.conn) {
return cached.conn
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
maxPoolSize: 10,
minPoolSize: 5,
socketTimeoutMS: 45000,
connectTimeoutMS: 10000,
serverSelectionTimeoutMS: 10000,
}
cached.promise = mongoose.connect(MONGODB_URI, opts)
}
try {
cached.conn = await cached.promise
console.log('Connected to MongoDB')
return cached.conn
} catch (error) {
cached.promise = null
console.error('MongoDB connection error:', error)
throw error
}
}
// Test MongoDB connection
export async function testMongoConnection(): Promise<boolean> {
try {
const connection = await connectDB()
// Test database operations
await connection.connection.db.admin().ping()
console.log('✅ MongoDB connection test successful')
// Optional: Test if we can create a test collection
const testCollection = connection.connection.db.collection('connection_test')
await testCollection.insertOne({ test: true, timestamp: new Date() })
await testCollection.deleteOne({ test: true })
console.log('✅ MongoDB read/write test successful')
return true
} catch (error) {
console.error('❌ MongoDB connection test failed:', error)
console.error('Please check:')
console.error('1. MongoDB is running (docker-compose up -d in /mongo directory)')
console.error('2. MONGODB_URI in .env is correct')
console.error('3. MongoDB credentials are valid')
return false
}
}
export default connectDB
export { connectDB }