adiljava's picture
feat: Implement API schemas and services for user authentication, plant care, chat, and scans
3b45a26
Raw
History Blame Contribute Delete
988 Bytes
from fastapi import HTTPException, status
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from core.config import settings
client: AsyncIOMotorClient | None = None
db: AsyncIOMotorDatabase | None = None
async def connect_to_mongo():
"""Connect to MongoDB."""
global client, db
client = AsyncIOMotorClient(settings.MONGODB_URL)
db = client[settings.MONGODB_DB_NAME]
# Force an actual round-trip so startup fails fast on bad URI/network/auth.
await client.admin.command("ping")
print("Connected to MongoDB")
async def close_mongo_connection():
"""Close MongoDB connection."""
global client
if client:
client.close()
print("Closed MongoDB connection")
def get_db() -> AsyncIOMotorDatabase:
"""Get database instance."""
if db is None:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Database is not initialized",
)
return db