pagination

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package pagination provides offset and cursor-based pagination support for database queries with filtering integration.

Index

Constants

View Source
const (
	// DefaultLimit is the default number of items per page.
	DefaultLimit = 20
	// MaxLimit is the maximum allowed items per page.
	MaxLimit = 100
	// MinLimit is the minimum allowed items per page.
	MinLimit = 1
)

Variables

View Source
var ErrInvalidCursor = errors.New("invalid cursor")

ErrInvalidCursor is returned when cursor decoding fails.

View Source
var SupportedOperators = []string{"eq", "ne", "gt", "gte", "lt", "lte", "contains", "in", "startswith", "endswith", "isnull"}

SupportedOperators lists all supported filter operators.

Functions

func BuildCondition

func BuildCondition(field, op string, value any) (query.Condition, error)

BuildCondition creates a query Condition from field, operator, and value.

func EncodeCursor

func EncodeCursor(c Cursor) string

EncodeCursor encodes a cursor struct to a base64 URL-safe string.

func MergeWhereClauses

func MergeWhereClauses(clauses ...*query.WhereClause) *query.WhereClause

MergeWhereClauses combines multiple WHERE clauses with AND logic.

func ParseFilterKey

func ParseFilterKey(key string) (field, op string)

ParseFilterKey parses a filter key in the format field[op] into field and operator. If no operator is specified, defaults to "eq".

func ParseFilters

func ParseFilters(r *http.Request, allowed []string) map[string]any

ParseFilters extracts filter parameters from an HTTP request. Only fields in the allowed list are extracted. Supports both field=value and field[op]=value formats.

func ParseQueryParams

func ParseQueryParams(r *http.Request, allowedFilters []string, allowedSorts []string) (PageRequest, map[string]any, []SortField)

ParseQueryParams extracts both pagination and filter parameters from an HTTP request.

Types

type Cursor

type Cursor struct {
	ID        string `json:"id"`
	Field     string `json:"field,omitempty"`
	Value     any    `json:"value,omitempty"`
	Direction string `json:"dir,omitempty"`
}

Cursor represents an encoded cursor for keyset pagination.

func DecodeCursor

func DecodeCursor(s string) (*Cursor, error)

DecodeCursor decodes a base64 URL-safe string to a cursor struct.

type FilterBuilder

type FilterBuilder struct {
	// contains filtered or unexported fields
}

FilterBuilder builds query WHERE clauses from filter parameters.

func NewFilterBuilder

func NewFilterBuilder() *FilterBuilder

NewFilterBuilder creates a new FilterBuilder.

func (*FilterBuilder) Allow

func (b *FilterBuilder) Allow(field string, ops ...string) *FilterBuilder

Allow registers a field with allowed operators. If no operators are specified, all operators are allowed.

func (*FilterBuilder) AllowAll

func (b *FilterBuilder) AllowAll(fields ...string) *FilterBuilder

AllowAll registers multiple fields with all operators allowed.

func (*FilterBuilder) Build

func (b *FilterBuilder) Build(params map[string]any) (*query.WhereClause, error)

Build parses filter parameters and builds a WHERE clause. Parameters should be in the format: field=value or field[op]=value

type FilterDef

type FilterDef struct {
	Field      string
	AllowedOps []string
}

FilterDef defines allowed filter operations for a field.

type PageInfo

type PageInfo struct {
	Total       *int64 `json:"total,omitempty"`
	Page        *int   `json:"page,omitempty"`
	Limit       int    `json:"limit"`
	HasNext     bool   `json:"has_next"`
	HasPrevious bool   `json:"has_previous"`
	NextCursor  string `json:"next_cursor,omitempty"`
	PrevCursor  string `json:"prev_cursor,omitempty"`
}

PageInfo contains pagination metadata for the response.

type PageRequest

type PageRequest struct {
	Type   PaginationType
	Page   int    // For offset pagination (1-indexed)
	Limit  int    // Items per page
	Cursor string // For cursor pagination (forward)
	After  string // Alias for cursor (forward pagination)
	Before string // For backward pagination
}

PageRequest contains pagination parameters from the request.

func DefaultPageRequest

func DefaultPageRequest() PageRequest

DefaultPageRequest returns a PageRequest with sensible defaults.

func ParsePageRequest

func ParsePageRequest(r *http.Request) PageRequest

ParsePageRequest extracts pagination parameters from an HTTP request.

func (*PageRequest) GetCursor

func (pr *PageRequest) GetCursor() string

GetCursor returns the cursor value, checking both Cursor and After fields.

func (*PageRequest) GetOffset

func (pr *PageRequest) GetOffset() int

GetOffset calculates the offset for offset-based pagination.

func (*PageRequest) IsCursorPagination

func (pr *PageRequest) IsCursorPagination() bool

IsCursorPagination returns true if cursor-based pagination is being used.

func (*PageRequest) Validate

func (pr *PageRequest) Validate()

Validate validates and normalizes the PageRequest.

type PageResponse

type PageResponse[T any] struct {
	Data       []T      `json:"data"`
	Pagination PageInfo `json:"pagination"`
}

PageResponse represents a paginated response with items and pagination metadata.

type PaginationType

type PaginationType string

PaginationType represents the type of pagination to use.

const (
	// PaginationOffset uses traditional page/offset pagination.
	PaginationOffset PaginationType = "offset"
	// PaginationCursor uses cursor-based (keyset) pagination.
	PaginationCursor PaginationType = "cursor"
)

type Paginator

type Paginator struct {
	// contains filtered or unexported fields
}

Paginator executes paginated queries against a database.

func NewPaginator

func NewPaginator(executor *query.Executor, entity string) *Paginator

NewPaginator creates a new Paginator for the given entity.

func (*Paginator) Execute

func (p *Paginator) Execute(ctx context.Context, req PageRequest) (*PageResponse[map[string]any], error)

Execute executes the paginated query based on the request type.

func (*Paginator) WithFields

func (p *Paginator) WithFields(fields []string) *Paginator

WithFields sets the fields to select.

func (*Paginator) WithInclude

func (p *Paginator) WithInclude(include []string) *Paginator

WithInclude sets the relations to include.

func (*Paginator) WithOrderBy

func (p *Paginator) WithOrderBy(orderBy []query.OrderClause) *Paginator

WithOrderBy sets the ORDER BY clauses for the paginator.

func (*Paginator) WithTotal

func (p *Paginator) WithTotal(include bool) *Paginator

WithTotal enables or disables total count in offset pagination.

func (*Paginator) WithWhere

func (p *Paginator) WithWhere(where *query.WhereClause) *Paginator

WithWhere sets the WHERE clause for the paginator.

type SortField

type SortField struct {
	Field string
	Desc  bool
}

SortField represents a sort field with direction.

func ParseSort

func ParseSort(r *http.Request, allowed []string) []SortField

ParseSort extracts sort parameters from an HTTP request. Supports formats: sort=field, sort=-field (descending), sort=field:asc, sort=field:desc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL