cursor pagination

This commit is contained in:
Mazyar
2026-05-16 15:51:18 +03:30
parent bcb345103f
commit 70f581da09
7 changed files with 405 additions and 111 deletions
+33 -14
View File
@@ -26,16 +26,19 @@ type APIError struct {
// Meta represents metadata for paginated responses
type Meta struct {
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Page int `json:"page"`
Pages int `json:"pages"`
Total int `json:"total,omitempty"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Page int `json:"page,omitempty"`
Pages int `json:"pages,omitempty"`
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more,omitempty"`
}
type Pagination struct {
Limit int `query:"limit" valid:"optional,range(1|100)" default:"20"`
Offset int `query:"offset" valid:"optional,range(0|1000000)" default:"0"`
Cursor string `query:"cursor" valid:"optional"`
SortBy string `query:"sort_by" valid:"optional"`
SortOrder string `query:"sort_order" valid:"optional,in(asc|desc)"`
}
@@ -210,22 +213,38 @@ func NewPagination(c echo.Context) *Pagination {
sortOrder = "desc"
}
cursor := c.QueryParam("cursor")
return &Pagination{
Limit: limit,
Offset: offset,
Cursor: cursor,
SortBy: sortBy,
SortOrder: sortOrder,
}
}
// Pagination calculates pagination metadata
// Response calculates offset-based pagination metadata.
func (p *Pagination) Response(total int64) *Meta {
pages := (total + int64(p.Limit) - 1) / int64(p.Limit)
return &Meta{
Total: int(total),
Limit: p.Limit,
Offset: p.Offset,
Page: int(p.Offset/p.Limit) + 1,
Pages: int(pages),
}
return p.ListMeta(total, "", false)
}
// ListMeta builds pagination metadata for list endpoints (offset and/or cursor).
// When total is negative, total/page/pages are omitted (count was skipped).
func (p *Pagination) ListMeta(total int64, nextCursor string, hasMore bool) *Meta {
meta := &Meta{
Limit: p.Limit,
Offset: p.Offset,
NextCursor: nextCursor,
HasMore: hasMore,
}
if total >= 0 {
pages := (total + int64(p.Limit) - 1) / int64(p.Limit)
meta.Total = int(total)
if p.Limit > 0 {
meta.Page = p.Offset/p.Limit + 1
}
meta.Pages = int(pages)
}
return meta
}