Pagination Tools - NFSandbox/sh_trade_backend GitHub Wiki

Taking into considerations that the system has lots of endpoints using Pagination to form the result, we provided a set of tools for pagination select and result validation.

Config Pagination

We encapsulated a Pydantic class PaginationConfig which could be used as a Body parameter for FastAPI endpoints. Also this config could be applied to a Select statement conveniently using stmt = PaginationConfig.use_on(stmt)

For more info, check out class docstring at schemes/general.py: PaginationConfig

Construct Result

Note that when return a paginated result, we need to attach the total size of the actual result with the page content. This would allow the frontend application to calculate the total page count of the result and let user to choose in range of allowed page index.

We provided two util class for this purpose:

  • PaginatedResult
  • PaginatedResultOut

Example

Construct PaginatedResult

The former one only take cares of providing the basic attributes of paginated result, the latter one is actually inherited from BaseModel of Pydantic and will take care of Model Validation using PaginatedResultOut.model_validate()

def get_list_of_result(...):
    ...
    return gene_sche.PaginationedResult(
        total=total, pagination=pagination, data=res
    )

Notice that we pass back the PaginationConfig that used while paginating, and also pass total as the total count of the result, data as the data of this page.

Construct PaginatedResultOut

def endpoint_function(...):
    paginated_res: PaginatedResult = ...
    return await gene_sche.validate_result(
        session,
        paginated_res,
        gene_sche.PaginatedResultOut[list[db_sche.NotificationOut]],
    )

As the code imply, we need to manually specify the target schema of PaginatedResultOut within its generic parameters.