paginate

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2020 License: MIT Imports: 12 Imported by: 35

README

Gorm Pagination

Simple way to paginate gorm result. Gorm Pagination is compatible for net/http or fasthttp. Also support for many frameworks are based on net/http or fasthttp.

Installation

go get -u github.com/morkid/paginate

Simple usage

See example below:

Paginate using http request

example paging, sorting and filtering:

  1. http://localhost:3000/?size=10&page=0&sort=-name
    produces:
    SELECT * FROM user ORDER BY name DESC LIMIT 10 OFFSET 0
    
    JSON response:
    {
        // result items
        "items": [
            {
                "id": 1,
                "name": "john",
                "age": 20
            }
        ],
        "page": 0, // current selected page
        "size": 10, // current limit or size per page
        "max_page": 0, // maximum page
        "total_pages": 1, // total pages
        "total": 1, // total matches including next page
        "visible": 1, // total visible on current page
        "last": true, // if response is first page
        "first": true // if response is last page
    }
    
  2. http://localhost:3000/?size=10&page=1&sort=-name,id
    produces:
    SELECT * FROM user ORDER BY name DESC, id ASC LIMIT 10 OFFSET 10
    
  3. http://localhost:3000/?filters=["name","john"]
    produces:
    SELECT * FROM user WHERE name = 'john' LIMIT 10 OFFSET 0
    
  4. http://localhost:3000/?filters=["name","like","john"]
    produces:
    SELECT * FROM user WHERE name LIKE '%john%' LIMIT 10 OFFSET 0
    
  5. http://localhost:3000/?filters=["age","between",[20, 25]]
    produces:
    SELECT * FROM user WHERE age BETWEEN (20 AND 25) LIMIT 10 OFFSET 0
    
  6. http://localhost:3000/?filters=[["name","like","john%25"],["OR"],["age","between",[20, 25]]]
    produces:
    SELECT * FROM user WHERE (
       (name LIKE '%john\%%' ESCAPE '\') OR (age BETWEEN (20 AND 25))
    ) LIMIT 10 OFFSET 0
    
  7. http://localhost:3000/?filters=[[["name","like","john"],["AND"],["name","not like","doe"]],["OR"],["age","between",[20, 25]]]
    produces:
    SELECT * FROM user WHERE (
       (
           (name LIKE '%john%')
                   AND
           (name NOT LIKE '%doe%')
       ) 
       OR 
       (age BETWEEN (20 AND 25))
    ) LIMIT 10 OFFSET 0
    
  8. http://localhost:3000/?filters=["name","IS NOT",null]
    produces:
    SELECT * FROM user WHERE name IS NOT NULL LIMIT 10 OFFSET 0
    
  9. Using POST method:
    curl -X POST \
    -H 'Content-type: application/json' \
    -d '{"page":"1","size":"20","sort":"-name","filters":["name","john"]}' \
    http://localhost:3000/
    

Example Usage

Net/HTTP Example
package main

import (
    "github.com/morkid/paginate"
    ...
)

func main() {
    // var db *gorm.DB
    pg := paginate.New()

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        model := db.Joins("User").Model(&Article{})
        paginated := pg.Response(model, r, &[]Article{})
        j, _ := json.Marshal(paginated)
        w.Header().Set("Content-type", "application/json")
        w.Write(j)
    })

    log.Fatal(http.ListenAndServe(":3000", nil))
}
Fasthttp Example
package main

import (
    "github.com/morkid/paginate"
    ...
)

func main() {
    // var db *gorm.DB
    pg := paginate.New()

    fasthttp.ListenAndServe(":3000", func(ctx *fasthttp.RequestCtx) {
        model := db.Joins("User").Model(&Article{})
        paginated := pg.Response(model, &ctx.Request, &[]Article{})
        j, _ := json.Marshal(paginated)
        ctx.SetContentType("application/json")
        ctx.SetBody(j)
    })
}
Fiber example
package main

import (
    "github.com/morkid/paginate"
    ...
)

func main() {
    // var db *gorm.DB
    pg := paginate.New()
    app := fiber.New()
    app.Get("/", func(c *fiber.Ctx) error {
        model := db.Joins("User").Model(&Article{})
        return c.JSON(pg.Response(model, c.Request(), &[]Article{}))
    })

    app.Listen(":3000")
}
Echo example
package main

import (
    "github.com/morkid/paginate"
    ...
)

func main() {
    // var db *gorm.DB
    pg := paginate.New()
    app := echo.New()
    app.GET("/", func(c echo.Context) error {
        model := db.Joins("User").Model(&Article{})
        return c.JSON(200, pg.Response(model, c.Request(), &[]Article{}))
    })

    app.Logger.Fatal(app.Start(":3000"))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Filters

func Filters(filterParams interface{}, p *PageRequest)

Filters func

Types

type Config

type Config struct {
	Operator     string
	FieldWrapper string
	ValueWrapper string
	DefaultPage  int64
	SmartSearch  bool
	Statement    *gorm.Statement `json:"-"`
}

Config struct

type Page

type Page struct {
	Items      interface{} `json:"items"`
	Page       int64       `json:"page"`
	Size       int64       `json:"size"`
	MaxPage    int64       `json:"max_page"`
	TotalPages int64       `json:"total_pages"`
	Total      int64       `json:"total"`
	Last       bool        `json:"last"`
	Fisrt      bool        `json:"first"`
	Visible    int64       `json:"visible"`
}

Page struct

type PageFilters

type PageFilters struct {
	Column      string
	Operator    string
	Value       interface{}
	ValuePrefix string
	ValueSuffix string
	Single      bool
	IsOperator  bool
}

PageFilters struct

type PageRequest

type PageRequest struct {
	Size    int
	Page    int
	Sorts   []SortOrder
	Filters PageFilters
	Config  Config `json:"-"`
}

PageRequest struct

func ParseRequest

func ParseRequest(r interface{}, config Config) PageRequest

ParseRequest func

type Pagination

type Pagination struct {
	Config *Config
	DB     *gorm.DB
}

Pagination struct

func New

func New(params ...interface{}) *Pagination

New func

func (*Pagination) Response

func (p *Pagination) Response(query *gorm.DB, req interface{}, res interface{}) Page

Response func

type Parameter

type Parameter struct {
	Page    string      `json:"page"`
	Size    string      `json:"size"`
	Sort    string      `json:"sort"`
	Order   string      `json:"order"`
	Filters interface{} `json:"filters"`
}

Parameter struct

type Query

type Query struct {
	WhereString string
	Wheres      []string
	Params      []interface{}
	Sorts       []SortOrder
	Limit       int
	Offset      int
}

Query struct

func Causes

func Causes(p PageRequest) Query

Causes func

type SortOrder

type SortOrder struct {
	Column    string
	Direction string
}

SortOrder struct

Jump to

Keyboard shortcuts

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