paginator

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2019 License: MIT Imports: 4 Imported by: 0

README

gorm-paginator

Build Status codecov Go Report Card GoDoc

A simple paginator for gorm. Also supports direct pagination via http.Request query parameters.

Installation

go get -u github.com/martinohmann/gorm-paginator

Usage

Basic usage
package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	paginator "github.com/martinohmann/gorm-paginator"
)

type model struct {
	gorm.Model
	Name string
}

func main() {
	db, err := gorm.Open("mysql", "root:root@tcp(mysql)/db?parseTime=true")
	if err != nil {
		panic(err)
	}

	var m []model

	options := []paginator.Option{
		paginator.WithPage(2),
		paginator.WithLimit(10),
		paginator.WithOrder("name DESC"),
	}

	res, err := paginator.Paginate(db, &m, options...)
	if err != nil {
		panic(err)
	}

	fmt.Printf("TotalRecords:   %d\n", res.TotalRecords)
	fmt.Printf("CurrentPage:    %d\n", res.CurrentPage)
	fmt.Printf("MaxPage:        %d\n", res.MaxPage)
	fmt.Printf("RecordsPerPage: %d\n", res.RecordsPerPage)
	fmt.Printf("IsFirstPage?:   %v\n", res.IsFirstPage())
	fmt.Printf("IsLastPage?:    %v\n", res.IsLastPage())

	for _, record := range res.Records.([]model) {
		fmt.Printf("ID:   %d", record.ID)
		fmt.Printf("Name: %s", record.Name)
	}
}
Pagination via http.Request query params
package main

import (
	"encoding/json"
	"net/http"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	paginator "github.com/martinohmann/gorm-paginator"
)

type model struct {
	gorm.Model
	Name string
}

func main() {
	db, err := gorm.Open("mysql", "root:root@tcp(mysql)/db?parseTime=true")
	if err != nil {
		panic(err)
	}

	// Example pagination request: /model?page=2&order=name+DESC&limit=10
	//
	// Check the godoc for paginator.WithRequest and paginator.ParamNames to
	// see how to configure the parameter names.
	http.Handle("/model", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var m []model

		res, err := paginator.Paginate(db, &m, paginator.WithRequest(r))
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
			return
		}

		json.NewEncoder(w).Encode(res)
	}))

	http.ListenAndServe(":8080", nil)
}

License

The source code of gorm-paginator is released under the MIT License. See the bundled LICENSE file for details.

Documentation

Overview

Package paginator provides a simple paginator implementation for gorm. It also supports configuring the paginator via http.Request query params.

Index

Constants

This section is empty.

Variables

View Source
var DefaultLimit = 20

DefaultLimit defines the default limit for paginated queries. This is a variable so that users can configure it at runtime.

View Source
var DefaultParamNames = ParamNames{"page", "limit", "order"}

DefaultParamNames specifies the query parameter names to use from a http.Request by default when the WithRequest option is uses. This can be overridden at runtime.

Functions

This section is empty.

Types

type Option

type Option func(p *paginator)

Option defines the signature of a paginator option function.

func WithLimit

func WithLimit(limit int) Option

WithLimit configures the limit of the paginator.

paginator.Paginate(db, &v, paginator.WithLimit(10))

func WithOrder

func WithOrder(order ...string) Option

WithOrder configures the order of the paginator.

paginator.Paginate(db, &v, paginator.WithOrder("name DESC", "id"))

func WithPage

func WithPage(page int) Option

WithPage configures the page of the paginator.

paginator.Paginate(db, &v, paginator.WithPage(2))

func WithRequest added in v0.1.0

func WithRequest(r *http.Request, paramNames ...ParamNames) Option

WithRequest configures the paginator from a *http.Request.

paginator.Paginate(db, &v, paginator.WithRequest(request))

paginator.Paginate(db, &v, paginator.WithRequest(request, paginator.ParamNames{
    Page: "page",
    Limit: "",       // Disable limit query param.
    Order: "order",
}))

type Paginator

type Paginator interface {
	// Paginate takes a value as arguments and returns a paginated result
	// containing records of the value type.
	Paginate(interface{}) (*Result, error)
}

Paginator defines the interface for a paginator.

func New

func New(db *gorm.DB, options ...Option) Paginator

New create a new value of the Paginator type. It expects a gorm DB handle and pagination options.

var v []SomeModel
p := paginator.New(db, paginator.WithPage(2))
res, err := p.Paginate(&v)

type ParamNames

type ParamNames struct {
	Page  string
	Limit string
	Order string
}

ParamNames defines a type to configure names of query parameters to use from a http.Request. If a field is set to the empty string, it will not be used.

type Result

type Result struct {
	CurrentPage    int         `json:"currentPage"`
	MaxPage        int         `json:"maxPage"`
	RecordsPerPage int         `json:"recordsPerPage"`
	TotalRecords   int         `json:"totalRecords"`
	Records        interface{} `json:"records"`
}

Result defines a paginated result.

func Paginate

func Paginate(db *gorm.DB, value interface{}, options ...Option) (*Result, error)

Paginate is a convenience wrapper for the paginator.

var v []SomeModel
res, err := paginator.Paginate(db, &v, paginator.WithPage(2))

func (*Result) IsFirstPage

func (r *Result) IsFirstPage() bool

IsFirstPage returns true if the current page of the result is the first page.

func (*Result) IsLastPage

func (r *Result) IsLastPage() bool

IsLastPage returns true if the current page of the result is the last page.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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