Added x-total-count response header
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolman.database import models
|
||||
@@ -41,12 +41,23 @@ async def find(
|
||||
sort_by: Optional[dict[str, SortOrder]] = None,
|
||||
limit: Optional[int] = None,
|
||||
offset: int = 0,
|
||||
) -> list[models.Vendor]:
|
||||
"""Find a list of vendor objects by search criteria."""
|
||||
) -> tuple[list[models.Vendor], int]:
|
||||
"""Find a list of vendor objects by search criteria.
|
||||
|
||||
Returns a tuple containing the list of items and the total count of matching items.
|
||||
"""
|
||||
stmt = select(models.Vendor)
|
||||
if name is not None:
|
||||
stmt = stmt.where(models.Vendor.name.ilike(f"%{name}%"))
|
||||
|
||||
total_count = None
|
||||
|
||||
if limit is not None:
|
||||
total_count_stmt = stmt.with_only_columns(func.count())
|
||||
total_count = (await db.execute(total_count_stmt)).scalar()
|
||||
|
||||
stmt = stmt.offset(offset).limit(limit)
|
||||
|
||||
if sort_by is not None:
|
||||
for fieldstr, order in sort_by.items():
|
||||
field = getattr(models.Vendor, fieldstr)
|
||||
@@ -55,11 +66,12 @@ async def find(
|
||||
elif order == SortOrder.DESC:
|
||||
stmt = stmt.order_by(field.desc())
|
||||
|
||||
if limit is not None:
|
||||
stmt = stmt.offset(offset).limit(limit)
|
||||
|
||||
rows = await db.execute(stmt)
|
||||
return list(rows.scalars().all())
|
||||
result = list(rows.scalars().all())
|
||||
if total_count is None:
|
||||
total_count = len(result)
|
||||
|
||||
return result, total_count
|
||||
|
||||
|
||||
async def update(
|
||||
|
||||
Reference in New Issue
Block a user