added get products

parent 7e14fdc7
......@@ -16,3 +16,6 @@ class ProductController(BaseController):
except ValidationError as e:
raise http_exc.HTTPBadRequestException(detail=f"Validation error: {str(e)}")
async def get_list(self, **kwargs):
return await self.product_service.get_product_list(**kwargs)
import fastapi as fa
from .ctrl import ProductController
from .schemas import ProductGetSchema
router = fa.APIRouter(prefix='/products', tags=['Product'])
......@@ -15,3 +16,8 @@ async def create_product(
price: float = fa.Form(...)
):
return await ctrl.create(name=name, description=description, price=price, image=image)
@router.get('')
async def get_products(page: int = 1, size: int = 10, params: ProductGetSchema = fa.Depends()):
return await ctrl.get_list(page=page, size=size, **params.model_dump(exclude_none=True))
......@@ -8,14 +8,10 @@ class ProductBaseSchema(BaseModel):
class ProductIdSchema(BaseModel):
id: UUID
id: UUID | None = None
model_config = ConfigDict(from_attributes=True)
class ProductListSchema(ProductBaseSchema, ProductIdSchema):
pass
class ProductGetSchema(ProductBaseSchema, ProductIdSchema):
description: str | None = None
price: float | None = None
......
......@@ -20,3 +20,12 @@ class ProductService:
)
return ProductGetSchema.model_validate(product)
async def get_product_list(self, **kwargs):
products = await self.product_repository.get_list(**kwargs)
return {
"page": products['page'],
"size": products['size'],
"total": products['total'],
"result": [ProductGetSchema.model_validate(product) for product in products['result']]
}
import math
from .base import BaseRepository
from ..models import Product
class ProductRepository(BaseRepository):
model = Product
async def get_list(self, page, size, **kwargs):
query = self.model.all()
offset_min = (page - 1) * size
offset_max = page * size
data = await query
result = {
"page": page,
"size": size,
"total": math.ceil(len(data) / size) - 1,
"result": data[offset_min:offset_max]
}
return result
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment