from __future__ import annotations from typing import Any from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase from app.configs.settings import Settings class MongoDatabase: def __init__(self, settings: Settings) -> None: self._settings = settings self._client: AsyncIOMotorClient[Any] | None = None self._database: AsyncIOMotorDatabase[Any] | None = None async def connect(self) -> None: self._client = AsyncIOMotorClient( self._settings.mongo.uri, maxPoolSize=self._settings.mongo.max_pool_size, minPoolSize=self._settings.mongo.min_pool_size, serverSelectionTimeoutMS=self._settings.mongo.connect_timeout_ms, uuidRepresentation="standard", ) self._database = self._client[self._settings.mongo.database] await self._database.command("ping") async def disconnect(self) -> None: if self._client is not None: self._client.close() self._client = None self._database = None @property def db(self) -> AsyncIOMotorDatabase[Any]: if self._database is None: msg = "MongoDB is not connected." raise RuntimeError(msg) return self._database