from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from fastapi import FastAPI from sqlalchemy.ext.asyncio import AsyncEngine from api.app_entrypoint.dependencies import init_dependencies from api.app_entrypoint.error_handlers import init_exc_handlers from api.infrastructure.auth.jwt_settings import JwtSettings from api.infrastructure.dependencies.adapters import create_engine from api.infrastructure.dependencies.configs import ( app_settings, get_db_settings, get_jwt_settings, ) from api.infrastructure.persistence.db_setings import DBSettings from api.infrastructure.persistence.models import Base from api.infrastructure.settings import Settings from .routers import init_routers @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator: app.dependency_overrides[DBSettings] = get_db_settings app.dependency_overrides[JwtSettings] = get_jwt_settings app.dependency_overrides[Settings] = app_settings app.dependency_overrides[AsyncEngine] = create_engine engine = app.dependency_overrides[AsyncEngine]( app.dependency_overrides[Settings]( app.dependency_overrides[DBSettings](), app.dependency_overrides[JwtSettings](), ), ) async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) yield def app_factory() -> FastAPI: app = FastAPI( lifespan=lifespan, ) init_dependencies(app) init_routers(app) init_exc_handlers(app) return app