repo.menu typehint

develop
Сергей Ванюшкин 2024-02-04 17:59:20 +03:00
parent 2754b82b5d
commit 5173fcd36c
2 changed files with 19 additions and 21 deletions

View File

@ -5,30 +5,31 @@ from sqlalchemy import delete, distinct, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased from sqlalchemy.orm import aliased
from fastfood import models, schemas from fastfood import schemas
from fastfood.dbase import get_async_session from fastfood.dbase import get_async_session
from fastfood.models import Dish, Menu, SubMenu
class MenuRepository: class MenuRepository:
def __init__(self, session: AsyncSession = Depends(get_async_session)): def __init__(self, session: AsyncSession = Depends(get_async_session)):
self.db = session self.db = session
async def get_menus(self): async def get_menus(self) -> list[Menu]:
query = select(models.Menu) query = select(Menu)
menus = await self.db.execute(query) menus = await self.db.execute(query)
return menus.scalars().all() return [x for x in menus.scalars().all()]
async def create_menu_item(self, menu: schemas.MenuBase): async def create_menu_item(self, menu: schemas.MenuBase) -> Menu:
new_menu = models.Menu(**menu.model_dump()) new_menu = Menu(**menu.model_dump())
self.db.add(new_menu) self.db.add(new_menu)
await self.db.commit() await self.db.commit()
await self.db.refresh(new_menu) await self.db.refresh(new_menu)
return new_menu return new_menu
async def get_menu_item(self, menu_id: UUID): async def get_menu_item(self, menu_id: UUID) -> Menu | None:
m = aliased(models.Menu) m = aliased(Menu)
s = aliased(models.SubMenu) s = aliased(SubMenu)
d = aliased(models.Dish) d = aliased(Dish)
query = ( query = (
select( select(
@ -51,19 +52,16 @@ class MenuRepository:
self, self,
menu_id: UUID, menu_id: UUID,
menu: schemas.MenuBase, menu: schemas.MenuBase,
): ) -> Menu:
query = ( query = update(Menu).where(Menu.id == menu_id).values(**menu.model_dump())
update(models.Menu)
.where(models.Menu.id == menu_id)
.values(**menu.model_dump())
)
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
qr = select(models.Menu).where(models.Menu.id == menu_id) qr = select(Menu).where(Menu.id == menu_id)
updated_menu = await self.db.execute(qr) updated_menu = await self.db.execute(qr)
return updated_menu return updated_menu.scalar_one()
async def delete_menu_item(self, menu_id: UUID): async def delete_menu_item(self, menu_id: UUID) -> int:
query = delete(models.Menu).where(models.Menu.id == menu_id) query = delete(Menu).where(Menu.id == menu_id)
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
return 200

View File

@ -52,7 +52,7 @@ async def update_menu(
menu_id=menu_id, menu_id=menu_id,
menu_data=menu, menu_data=menu,
) )
return result.scalars().one() return result
@router.delete('/{menu_id}') @router.delete('/{menu_id}')