Pager (Pager v1.0.0)
View SourceProvides pagination functionality for Ecto queries.
This module offers a simple way to paginate Ecto query results with automatic handling of page boundaries, flexible parameter types, and consistent return structure.
Summary
Types
Pagination result containing pagination metadata and list of items.
Functions
Paginates an Ecto query with flexible parameter handling.
Types
@type page_result() :: %{ has_next: boolean(), has_prev: boolean(), prev_page: integer(), page: integer(), next_page: integer(), first: integer(), last: integer(), count: integer(), list: [any()] }
Pagination result containing pagination metadata and list of items.
Fields:
has_next
- Indicates if there are more pages after the current onehas_prev
- Indicates if there are pages before the current oneprev_page
- Previous page numberpage
- Current page numbernext_page
- Next page numberfirst
- Index of first item on current pagelast
- Index of last item on current pagecount
- Total number of items across all pageslist
- List of results/items on the current page
Functions
@spec page( Ecto.Query.t(), Ecto.Repo.t(), integer() | binary() | nil, integer() | binary() | nil ) :: page_result()
Paginates an Ecto query with flexible parameter handling.
Parameters
query
- An Ecto query to paginaterepo
- The Ecto repo to execute the querypage
- Page number (integer or string, defaults to 1)per_page
- Items per page (integer or string, defaults to 50)
Examples
iex> alias Pager.{User, Repo}
iex> query = from(u in User)
iex> result = Pager.page(query, Repo, 1, 20)
iex> Map.drop(result, [:list])
%{count: 0, first: 1, has_next: false, has_prev: false, last: 0, next_page: 2, page: 1, prev_page: 0}
# String parameters (e.g. from Phoenix params)
iex> alias Pager.{User, Repo}
iex> query = from(u in User)
iex> result = Pager.page(query, Repo, "2", "10")
iex> Map.drop(result, [:list])
%{count: 0, first: 11, has_next: false, has_prev: true, last: 0, next_page: 3, page: 2, prev_page: 1}
# With defaults
iex> alias Pager.{User, Repo}
iex> query = from(u in User)
iex> result = Pager.page(query, Repo, nil, 50)
iex> Map.drop(result, [:list])
%{count: 0, first: 1, has_next: false, has_prev: false, last: 0, next_page: 2, page: 1, prev_page: 0}