Documentation
¶
Overview ¶
Package pagination holds the data types of a paginated list: the page options a client sends in the URL, the page envelope a server answers with and the list filter both share. It imports only the standard library, so a client can use the same types as the server without the framework.
The server side (Context.BindPagination, Context.Paginated, AllowSort, DenySort) lives in package context, which aliases these types.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // MaxPageSize defines the max size of items to display. MaxPageSize = 100000 // DefaultPageSize defines the default size when PageOptions.Size is zero. DefaultPageSize = 100 )
The page size bounds of PageOptions.GetLimit. Set them once, at start-up; iris.Patches().Context().SetMaxPageSize and SetDefaultPageSize do the same.
var ErrSortNotAllowed = errors.New("sort column not allowed")
ErrSortNotAllowed is the error ListFilter.SortColumn wraps when the client asked to sort by a column the endpoint does not offer. A sort column reaches an ORDER BY clause, so the allowed set is stated by the endpoint and never taken from the request.
Functions ¶
func CountToInt64 ¶
CountToInt64 converts a total count to the Page's int64. Integer counts convert exactly; a float count rounds half up (2.5 becomes 3), because a fractional total can only come from an aggregate and truncating it could hide the last page.
It is exported so that every door into NewPage answers the same: the MVC list handlers take their own total from the service and must not truncate what Paginated rounds.
Types ¶
type CountResponse ¶
type CountResponse[N CountType] struct { Count N `json:"count"` }
CountResponse is a generic response for a count operation.
type CountType ¶
type CountType interface {
constraints.Number
}
CountType is a type that can be used as a total count of the items in a list.
type ListFilter ¶
type ListFilter struct {
Term string `json:"term,omitzero" url:"term"`
Names []string `json:"names,omitzero" url:"names"`
Substring bool `json:"substring,omitzero" url:"substring"`
Sort string `json:"sort,omitzero" url:"sort"`
SortDescending bool `json:"sort_descending,omitzero" url:"sort_descending"`
}
ListFilter is the request half every list endpoint shares: the free-text term, an explicit set of names, the substring switch and the sort request. Embed it in a service's own filter and keep only the fields that service adds.
It carries both tag sets on purpose: the JSON one for the POST or QUERY /list body and the url one for a GET list route read through Context.ReadQuery.
func (ListFilter) SortColumn ¶
func (f ListFilter) SortColumn(allowed ...string) (string, error)
SortColumn returns the requested sort column when it is one of "allowed". An empty sort request answers ("", nil), so the caller keeps its own default ordering. A column outside the list answers an error wrapping ErrSortNotAllowed and naming the column.
func (ListFilter) SortOrder ¶
func (f ListFilter) SortOrder() string
SortOrder returns the SQL sort direction of the request: "DESC" when SortDescending is set, "ASC" otherwise.
func (ListFilter) SortRequest ¶
func (f ListFilter) SortRequest() (column string, descending bool, requested bool)
SortRequest returns the sort request as the sort policy options read it: the trimmed column, the direction and whether a sort was asked for at all.
It is the method AllowSort and DenySort look for, so a service's own filter type takes the policy by embedding ListFilter and nothing else.
type Page ¶
type Page[T any] struct { CurrentPage int `json:"current_page"` // the current page. PageSize int `json:"page_size"` // the total amount of the entities return. TotalPages int `json:"total_pages"` // the total number of pages based on page, size and total count. TotalItems int64 `json:"total_items"` // the total number of rows. HasNextPage bool `json:"has_next_page"` // true if more data can be fetched, depending on the current page * page size and total pages. Filter any `json:"filter"` // if any filter data. Items []T `json:"items"` // Items is empty array if no objects returned. Do NOT modify from outside. }
Page is the http response of a server handler which should render items with pagination support.
func NewPage ¶
func NewPage[T any](opts PageOptions, filter any, items []T, totalCount int64) *Page[T]
NewPage returns a new Page response which holds the current page, page size, total pages, total items count, any custom filter and the items array.
Example Code:
import "github.com/kataras/iris/v14/core/pkg/pagination"
...more code
type User struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
}
type ExtraUser struct {
User
ExtraData string
}
func main() {
users := []User{
{"Gerasimos", "Maropoulos"},
{"Efi", "Kwfidou"},
}
t := pagination.NewPage(pagination.PageOptions{Page: 1, Size: 50}, nil, users, 100)
// Optionally, transform a T list of objects to a V list of objects.
v, err := t.Transform[ExtraUser](func(u User) (ExtraUser, error) {
return ExtraUser{
User: u,
ExtraData: "test extra data",
}, nil
})
if err != nil { panic(err) }
paginationJSON, err := json.MarshalIndent(v, "", " ")
if err!=nil { panic(err) }
fmt.Println(string(paginationJSON))
}
func (*Page[T]) Transform ¶
Transform accepts a Page response and converts to a list of V items. T => from V => to
Example Code:
listOfUsers := NewPage(...)
newPageOfExtraUsers, err := listOfUsers.Transform[ExtraUser](func(u User) (ExtraUser, error) {
return ExtraUser{
User: u,
ExtraData: "test extra data",
}, nil
})
type PageOptions ¶
type PageOptions struct {
// Current page number.
// If Page > 0 then:
// Limit = Size
// Offset = Limit * (Page - 1), see the GetOffset method.
// If Page == 0 then no actual data is return,
// internally we must check for this value
// because in postgres LIMIT 0 returns the columns but with an empty set.
Page int `json:"page" url:"page"`
// The elements to get, this modifies the LIMIT clause,
// this Size can't be higher than the MaxPageSize.
// If Size is zero then size is set to DefaultPageSize.
Size int `json:"size" url:"size"`
// Details determinates if the server should return nested objects or not.
Details bool `json:"details" url:"details"`
}
PageOptions is the list request object which should be provided by the client through URL Query. Then the server passes that options to a database query, including any custom filters may be given from the request body and, then the server responds back with a `Context.JSON(NewPage(...))` response based on the database query's results.
func (*PageOptions) Bind ¶
func (opts *PageOptions) Bind(r *http.Request) error
Bind binds the PageOptions values to a request value. It should be used as an client.RequestOption to fire requests on a server that supports, e.g.
resp, err := c.Do(ctx, "QUERY", "/u/list", filter, page.Bind)
func (*PageOptions) GetCurrentPage ¶
func (opts *PageOptions) GetCurrentPage() int
GetCurrentPage returns the Page or 1.
func (*PageOptions) GetLimit ¶
func (opts *PageOptions) GetLimit() int
GetLimit returns the LIMIT value of a query: Size, or DefaultPageSize when Size is not positive, clamped to MaxPageSize when that is positive. The result is always positive, so it is safe as a divisor and as a LIMIT even when the package variables are misconfigured to zero.
func (*PageOptions) GetNextPage ¶
func (opts *PageOptions) GetNextPage() int
GetNextPage returns the next page, current page + 1.
func (*PageOptions) GetOffset ¶
func (opts *PageOptions) GetOffset() int
GetOffset returns the OFFSET value of a query.
type SortRequester ¶
SortRequester is the interface a decoded filter is checked against by the sort policy options (context.AllowSort and context.DenySort). ListFilter implements it, so any filter embedding it does too; a filter without it is not subject to a policy.