Skip to content

Commit

Permalink
fix(api): reuse session through all the request
Browse files Browse the repository at this point in the history
  • Loading branch information
betofigueiredo committed May 22, 2024
1 parent e7a10a6 commit 40cfb84
Show file tree
Hide file tree
Showing 19 changed files with 152 additions and 171 deletions.
14 changes: 7 additions & 7 deletions api/src/controllers/drinks_controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
GetSimilarDrinksResponse,
)
from fastapi import APIRouter, Depends
from infrastructure.core.database import get_db_session
from infrastructure.core.database import get_session
from infrastructure.repositories.repository import Repository
from sqlalchemy.ext.asyncio import AsyncSession
from use_cases.drinks import (
Expand All @@ -28,7 +28,7 @@ async def get_drinks(
search: Optional[str] = None,
calories: Optional[str] = None,
alcoholic_content: Optional[str] = None,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetDrinksResponse | ErrorResponse:
return await get_drinks_use_case(
query_params={
Expand All @@ -40,29 +40,29 @@ async def get_drinks(
"alcoholic_content": alcoholic_content,
},
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)


@router.get("/{drink_id}", response_model=GetDrinkResponse)
async def get_drink(
drink_id: str,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetDrinkResponse | ErrorResponse:
return await get_drink_use_case(
drink_id=drink_id,
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)


@router.get("/{drink_id}/similar", response_model=GetSimilarDrinksResponse)
async def get_similar_drinks(
drink_id: str,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetSimilarDrinksResponse | ErrorResponse:
return await get_similar_drinks_use_case(
drink_id=drink_id,
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)
10 changes: 5 additions & 5 deletions api/src/controllers/highlights_controllers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from custom_types import ErrorResponse, GetHighlightResponse, GetHighlightsResponse
from fastapi import APIRouter, Depends
from infrastructure.core.database import get_db_session
from infrastructure.core.database import get_session
from infrastructure.repositories.repository import Repository
from sqlalchemy.ext.asyncio import AsyncSession
from use_cases.highlights import get_highlight_use_case, get_highlights_use_case
Expand All @@ -11,20 +11,20 @@

@router.get("/", response_model=GetHighlightsResponse)
async def get_highlights(
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetHighlightsResponse | ErrorResponse:
return await get_highlights_use_case(
repository=Repository(db_session),
repository=Repository(session),
)


@router.get("/{highlight_id}", response_model=GetHighlightResponse)
async def get_highlight(
highlight_id: str,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetHighlightResponse | ErrorResponse:
return await get_highlight_use_case(
highlight_id=highlight_id,
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)
10 changes: 5 additions & 5 deletions api/src/controllers/instructions_controllers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from custom_types import ErrorResponse, GetInstructionResponse, GetInstructionsResponse
from fastapi import APIRouter, Depends
from infrastructure.core.database import get_db_session
from infrastructure.core.database import get_session
from infrastructure.repositories.repository import Repository
from sqlalchemy.ext.asyncio import AsyncSession
from use_cases.instructions import get_instruction_use_case, get_instructions_use_case
Expand All @@ -11,20 +11,20 @@

@router.get("/", response_model=GetInstructionsResponse)
async def get_instructions(
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetInstructionsResponse | ErrorResponse:
return await get_instructions_use_case(
repository=Repository(db_session),
repository=Repository(session),
)


@router.get("/{instruction_id}", response_model=GetInstructionResponse)
async def get_instruction(
instruction_id: str,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetInstructionResponse | ErrorResponse:
return await get_instruction_use_case(
instruction_id=instruction_id,
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)
10 changes: 5 additions & 5 deletions api/src/controllers/knowledges_controllers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from custom_types import ErrorResponse, GetKnowledgeResponse, GetKnowledgesResponse
from fastapi import APIRouter, Depends
from infrastructure.core.database import get_db_session
from infrastructure.core.database import get_session
from infrastructure.repositories.repository import Repository
from sqlalchemy.ext.asyncio import AsyncSession
from use_cases.knowledges import get_knowledge_use_case, get_knowledges_use_case
Expand All @@ -11,20 +11,20 @@

@router.get("/", response_model=GetKnowledgesResponse)
async def get_knowledges(
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetKnowledgesResponse | ErrorResponse:
return await get_knowledges_use_case(
repository=Repository(db_session),
repository=Repository(session),
)


@router.get("/{knowledge_slug}", response_model=GetKnowledgeResponse)
async def get_knowledge(
knowledge_slug: str,
db_session: AsyncSession = Depends(get_db_session),
session: AsyncSession = Depends(get_session),
) -> GetKnowledgeResponse | ErrorResponse:
return await get_knowledge_use_case(
knowledge_slug=knowledge_slug,
utils=Utils(),
repository=Repository(db_session),
repository=Repository(session),
)
9 changes: 3 additions & 6 deletions api/src/infrastructure/core/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
create_async_engine,
)

engine: AsyncEngine = create_async_engine(settings.DB_URL)
engine: AsyncEngine = create_async_engine(settings.DB_URL, pool_recycle=3600)


Session = async_sessionmaker(
Expand All @@ -20,9 +20,6 @@
)


async def get_db_session() -> AsyncGenerator[Any, Any]:
session = Session()
try:
async def get_session() -> AsyncGenerator[Any, Any]:
async with Session() as session:
yield session
finally:
await session.close()
10 changes: 5 additions & 5 deletions api/src/infrastructure/repositories/drinks/drinks_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@


class DrinksRepository:
def __init__(self, db_session: AsyncSession):
self.db_session = db_session
def __init__(self, session: AsyncSession):
self.session = session

async def find_all(
self,
Expand All @@ -23,7 +23,7 @@ async def find_all(
alcoholic_content: str | None,
) -> Tuple[List[Drink], int]:
return await find_all_drinks(
db_session=self.db_session,
session=self.session,
page=page,
per_page=per_page,
category=category,
Expand All @@ -33,13 +33,13 @@ async def find_all(
)

async def find_by_id(self, drink_id: int) -> Drink | None:
return await find_drink_by_id(db_session=self.db_session, drink_id=drink_id)
return await find_drink_by_id(session=self.session, drink_id=drink_id)

async def find_similar(
self, drink_id: int, categories: List[int], ingredients: List[str]
) -> List[Drink]:
return await find_similar_drinks(
db_session=self.db_session,
session=self.session,
drink_id=drink_id,
categories=categories,
ingredients=ingredients,
Expand Down
119 changes: 57 additions & 62 deletions api/src/infrastructure/repositories/drinks/queries/find_all_drinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,89 +8,84 @@


async def find_all_drinks(
db_session: AsyncSession,
session: AsyncSession,
page: int,
per_page: int,
category: str | None,
search: str | None,
calories: str | None,
alcoholic_content: str | None,
) -> Tuple[List[Drink], int]:
async with db_session as session:
list_query = select(Drink).options(selectinload(Drink.ingredients))
count_query = select(func.count(Drink.id))
list_query = select(Drink).options(selectinload(Drink.ingredients))
count_query = select(func.count(Drink.id))

if category:
categories = (
[category, "scaipirinhas"] if category == "caipirinhas" else [category]
)
list_query = list_query.where(
Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories))
)
if category:
categories = (
[category, "scaipirinhas"] if category == "caipirinhas" else [category]
)
list_query = list_query.where(
Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories))
)
count_query = count_query.where(
Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories))
)
)
count_query = count_query.where(
Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories))
)
else:
categories_to_exclude = ["caipirinhas", "scaipirinhas"]
list_query = list_query.where(
~Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories_to_exclude))
)
)
else:
categories_to_exclude = ["caipirinhas", "scaipirinhas"]
list_query = list_query.where(
~Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories_to_exclude))
)
count_query = count_query.where(
~Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories_to_exclude))
)
)
count_query = count_query.where(
~Drink.categories.any(
DrinkCategory.category.has(Category.name.in_(categories_to_exclude))
)
)

if search:
list_query = list_query.where(
(
Drink.ingredients.any(
Ingredient.ingredient_type.has(
IngredientType.name.like(f"%{search}%")
)
if search:
list_query = list_query.where(
(
Drink.ingredients.any(
Ingredient.ingredient_type.has(
IngredientType.name.like(f"%{search}%")
)
)
| (Drink.name.like(f"%{search}%"))
)
count_query = count_query.where(
(
Drink.ingredients.any(
Ingredient.ingredient_type.has(
IngredientType.name.like(f"%{search}%")
)
| (Drink.name.like(f"%{search}%"))
)
count_query = count_query.where(
(
Drink.ingredients.any(
Ingredient.ingredient_type.has(
IngredientType.name.like(f"%{search}%")
)
)
| (Drink.name.like(f"%{search}%"))
)
| (Drink.name.like(f"%{search}%"))
)

if calories:
list_query = list_query.where(Drink.calories >= calories.split("-")[0])
count_query = count_query.where(Drink.calories >= calories.split("-")[0])
if calories.split("-")[1]:
list_query = list_query.where(Drink.calories <= calories.split("-")[1])
count_query = count_query.where(
Drink.calories <= calories.split("-")[1]
)
if calories:
list_query = list_query.where(Drink.calories >= calories.split("-")[0])
count_query = count_query.where(Drink.calories >= calories.split("-")[0])
if calories.split("-")[1]:
list_query = list_query.where(Drink.calories <= calories.split("-")[1])
count_query = count_query.where(Drink.calories <= calories.split("-")[1])

if alcoholic_content:
list_query = list_query.where(Drink.alcoholic_content == alcoholic_content)
count_query = count_query.where(
Drink.alcoholic_content == alcoholic_content
)
if alcoholic_content:
list_query = list_query.where(Drink.alcoholic_content == alcoholic_content)
count_query = count_query.where(Drink.alcoholic_content == alcoholic_content)

list_query = (
list_query.order_by(asc(Drink.name))
.limit(per_page)
.offset((page - 1) * per_page)
)
list_query = (
list_query.order_by(asc(Drink.name))
.limit(per_page)
.offset((page - 1) * per_page)
)

drinks = await session.scalars(list_query)
total_count = await session.scalar(count_query) or 0
drinks = await session.scalars(list_query)
total_count = await session.scalar(count_query) or 0

return list(drinks), total_count
return list(drinks), total_count
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
from sqlalchemy.future import select


async def find_drink_by_id(db_session: AsyncSession, drink_id: int) -> Drink | None:
async with db_session as session:
query = select(Drink).where(Drink.old_id == drink_id)
result = await session.execute(query)
return result.scalars().unique().one_or_none()
async def find_drink_by_id(session: AsyncSession, drink_id: int) -> Drink | None:
query = select(Drink).where(Drink.old_id == drink_id)
result = await session.execute(query)
return result.scalars().unique().one_or_none()
Loading

0 comments on commit 40cfb84

Please sign in to comment.