lister

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: ISC Imports: 7 Imported by: 0

README

Lister Package

GitHub Tag Go Reference License Go Report Card Contributors Issues

The lister package simplifies pagination, sorting, filtering, and metadata handling for data queries. It also provides tools to generate SQL-compatible clauses and build structured responses.

Installation

go get github.com/go-universal/lister

Features

  • Pagination: Manage page numbers and limits and calculate pagination data.
  • Sorting: Add multiple sort fields and orders.
  • Filtering: Apply key-value filters.
  • Metadata: Add and retrieve custom metadata.

Usage

Create a Lister

You can create a Lister instance using the following constructors:

  • Basic Constructor:
lister.New(options...)
  • From Parameters:
lister.NewFromParams(params, options...)
  • From JSON:
lister.NewFromJson(jsonString, options...)
  • From Base64 JSON:
lister.NewFromBase64Json(base64String, options...)

Methods

Pagination
  • SetPage(page uint64) Lister: Set the current page number for pagination control.
  • Page() uint64: Get the current page number.
  • SetLimit(limit uint) Lister: Set the maximum number of items per page.
  • Limit() uint: Get the current limit of items per page.
  • SetTotal(total uint64) Lister: Set the total number of available records. This method must be called to calculate pagination data.
  • Total() uint64: Get the total number of available records.
  • Pages() uint64: Calculate the total number of pages based on the total record count and limit per page.
  • From() uint64: Calculate the starting position of records for the current page.
  • To() uint64: Calculate the ending position of records for the current page.
Sorting
  • AddSort(sort string, order Order) Lister: Add a sorting condition. The sort parameter specifies the field to sort by, and order specifies the sorting order (asc or desc).
  • Sort() []Sort: Get the current active sorting configuration.
Searching
  • SetSearch(search string) Lister: Set a search keyword or phrase for filtering results.
  • Search() string: Get the current search keyword or phrase.
Filtering
  • SetFilters(filters map[string]any) Lister: Set multiple filters using a map of key-value pairs.
  • AddFilter(key string, value any) Lister: Add a single filter condition using a key-value pair.
  • Filters() map[string]any: Get all applied filters as a map.
  • Filter(key string) any: Get the value of a specific filter by its key.
  • HasFilter(key string) bool: Check whether a filter exists for the specified key.
  • CastFilter(key string) cast.Caster: Convert a filter value for a specified key into a caster type for flexible data handling.
Metadata
  • AddMeta(key string, value any) Lister: Add metadata identified by a key.
  • Meta(key string) any: Get the metadata value for the specified key.
  • HasMeta(key string) bool: Check whether metadata exists for the specified key.
  • MetaData() map[string]any: Get all metadata as a map.
  • CastMeta(key string) cast.Caster: Convert a metadata value for a specified key into a caster type for flexible data handling.
SQL Generation
  • SQLSortOrder() string: Generate an SQL-compatible string representing the ORDER BY and LIMIT conditions.
Response
  • Response() map[string]any: Build a standardized JSON response containing pagination details and metadata.
  • ResponseWithData(data any) map[string]any: Build a JSON response with additional data, combined with pagination and metadata details.

Examples

Basic Usage
package main

import (
    "fmt"
    "github.com/go-universal/lister"
)

func main() {
    l := lister.New().
        SetPage(1).
        SetLimit(10).
        AddSort("name", "asc")

    fmt.Println("Page:", l.Page())
    fmt.Println("Limit:", l.Limit())
    fmt.Println("SQL Sort Order:", l.SQLSortOrder())
}
Using JSON Constructor
package main

import (
    "fmt"
    "github.com/go-universal/lister"
)

func main() {
    raw := `{
        "page": 2,
        "limit": 20,
        "sorts": [
            { "field": "name", "order": "desc" }
        ]
    }`

    l, err := lister.NewFromJson(raw)
    if err != nil {
        panic(err)
    }
    l.SetTotal(125)

    fmt.Println("Page:", l.Page())
    fmt.Println("Limit:", l.Limit())
    fmt.Println("Total Pages:", l.Pages())
    fmt.Println("SQL Sort Order:", l.SQLSortOrder())
}
Using Base64 JSON Constructor
package main

import (
    "encoding/base64"
    "fmt"
    "github.com/go-universal/lister"
)

func main() {
    encoded := base64.URLEncoding.EncodeToString([]byte(`{
        "page": 1,
        "limit": 25,
        "sorts": [
            { "field": "name", "order": "asc" }
        ]
    }`))

    l, err := lister.NewFromBase64Json(encoded)
    if err != nil {
        panic(err)
    }
    l.SetTotal(125)

    fmt.Println("Page:", l.Page())
    fmt.Println("Limit:", l.Limit())
    fmt.Println("Total Pages:", l.Pages())
    fmt.Println("SQL Sort Order:", l.SQLSortOrder())
}

License

This project is licensed under the ISC License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Lister

type Lister interface {
	// SetPage sets the current page number for pagination control.
	SetPage(page uint64) Lister

	// Page retrieves the current page number.
	Page() uint64

	// Pages returns the total number of pages based on the total record count and limit per page.
	Pages() uint64

	// SetLimit specifies the maximum number of items per page.
	SetLimit(limit uint) Lister

	// Limit retrieves the current limit of items per page.
	Limit() uint

	// AddSort appends a new sorting condition to the list of sorting criteria.
	// 'sort' defines the field to sort by, while 'order' specifies ascending or descending order.
	AddSort(sort string, order Order) Lister

	// Sort returns the current active sorting configuration.
	Sort() []Sort

	// SetSearch defines the search keyword or phrase for filtering results.
	SetSearch(search string) Lister

	// Search retrieves the current search keyword or phrase.
	Search() string

	// SetFilters assigns a map of key-value pairs to filter data.
	SetFilters(filters map[string]any) Lister

	// AddFilter assigns a single filter condition using a key-value pair.
	AddFilter(key string, value any) Lister

	// Filters returns the current set of applied filters.
	Filters() map[string]any

	// Filter retrieves the value of a specified filter.
	Filter(key string) any

	// HasFilter checks whether a filter exists for the specified key.
	HasFilter(key string) bool

	// CastFilter converts a filter value for a specified key into a caster type for flexible data handling.
	CastFilter(key string) cast.Caster

	// AddMeta assigns a meta-information value identified by a key.
	AddMeta(key string, value any) Lister

	// Meta retrieves the metadata value for the given key.
	Meta(key string) any

	// HasMeta checks whether metadata exists for the specified key.
	HasMeta(key string) bool

	// MetaData retrieves the complete metadata list as a map.
	MetaData() map[string]any

	// CastMeta converts a metadata value for a specified key into a caster type for flexible data handling.
	CastMeta(key string) cast.Caster

	// SetTotal sets the total number of available records.
	// This method must called after all sets.
	SetTotal(total uint64) Lister

	// Total retrieves the total number of available records.
	Total() uint64

	// From calculates the starting position of records for the current page.
	From() uint64

	// To calculates the ending position of records for the current page.
	To() uint64

	// SQLSortOrder generates an SQL-compatible string representing the ORDER BY and LIMIT conditions.
	SQLSortOrder() string

	// Response builds a standardized JSON response containing pagination details and metadata.
	Response() map[string]any

	// ResponseWithData generates a JSON response with additional data, combined with pagination and metadata details.
	ResponseWithData(data any) map[string]any
}

Lister provides a comprehensive set of methods to manage pagination, sorting, filtering, metadata, and response structures for data queries.

func New

func New(options ...Options) Lister

New creates a new instance of the Lister interface with customizable options.

func NewFromBase64Json

func NewFromBase64Json(data string, options ...Options) (Lister, error)

NewFromBase64Json creates a new Lister instance from a Base64-URL-encoded JSON string.

func NewFromJson

func NewFromJson(data string, options ...Options) (Lister, error)

NewFromJson creates a new Lister instance from a JSON string.

func NewFromParams

func NewFromParams(params ListerParams, options ...Options) Lister

NewFromParams creates a new Lister instance using the provided parameters.

type ListerParams

type ListerParams struct {
	Page    uint64         `json:"page"`
	Limit   uint           `json:"limit"`
	Sorts   []Sort         `json:"sorts"`
	Search  string         `json:"search"`
	Filters map[string]any `json:"filters"`
}

ListerParams represents the input parameters for creating a Lister. It includes pagination, sorting, search, and filtering options.

type Options

type Options func(*option)

Options defines a function type for modifying lister options.

func WithDefaultLimit

func WithDefaultLimit(def uint) Options

WithDefaultLimit sets the default query limit.

func WithDefaultSort

func WithDefaultSort(def string) Options

WithDefaultSort sets the default sort field.

func WithLimits

func WithLimits(def uint, valids ...uint) Options

WithLimits configures the default limit and allowed limits for lister.

func WithMySQLSorter

func WithMySQLSorter() Options

WithMySQLSorter configures the SQL sorter to use MySQL syntax.

func WithPostgreSQLSorter

func WithPostgreSQLSorter() Options

WithPostgreSQLSorter configures the SQL sorter to use PostgreSQL syntax.

func WithSorts

func WithSorts(def string, valids ...string) Options

WithSorts configures the default sort field and allowed sort fields for lister.

type Order

type Order string

Order represents the sorting order.

const (
	// Ascending indicates ascending order.
	Ascending Order = "asc"

	// Descending indicates descending order.
	Descending Order = "desc"
)

func ParseOrder

func ParseOrder(v any) Order

ParseOrder converts a value into an Order. Returns Descending for "-1" or "desc", otherwise Ascending.

func (Order) Numeric

func (order Order) Numeric() int

Numeric returns 1 for Ascending and -1 for Descending.

func (Order) String

func (order Order) String() string

String returns the uppercase string representation of the Order.

type SQLSortGenerator

type SQLSortGenerator func(sorts []Sort, from uint64, limit uint) string

SQLSortGenerator defines a function type for generating SQL ORDER BY clauses.

type Sort

type Sort struct {
	Field string `json:"field"` // Field to sort by
	Order Order  `json:"order"` // Sorting order (ASC or DESC)
}

Sort represents a sorting field and its order (ascending or descending).

Jump to

Keyboard shortcuts

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