Files
thePlug/app/core/mongodb.py

36 lines
972 B
Python

from core.config import settings
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
class _MongoDB:
client: AsyncIOMotorClient | None = None
def get_database(self) -> AsyncIOMotorDatabase:
if self.client is None:
raise RuntimeError("MongoDB client has not been initialized")
return self.client[settings.MONGODB_DB_NAME]
mongodb = _MongoDB()
async def init_mongodb() -> None:
mongodb.client = AsyncIOMotorClient(settings.MONGODB_URI)
await ensure_mongodb_available()
async def close_mongodb() -> None:
client = mongodb.client
mongodb.client = None
if client is not None:
client.close()
async def get_database() -> AsyncIOMotorDatabase:
return mongodb.get_database()
async def ensure_mongodb_available() -> None:
client = mongodb.client
if client is None:
raise RuntimeError("MongoDB client has not been initialized")
await client.admin.command("ping")