pagination

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2020 License: MIT Imports: 6 Imported by: 0

README

gorm-pagination

Pagination with gorm and net/http

Actions Status

Usage

Example (Error handling is omitted)

package main

import (
    "net/http"
    "github.com/jinzhu/gorm"
	pagination "github.com/maruware/gorm-pagination"
)

type Sample struct {
	db *gorm.DB
}
func (s *Sample) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    q := s.db.Model(Post{})
    var total uint
    q, _ := pagination.PagenateWithContext(r.Context(), q, &total)

    var posts []Post
    q.Find(&posts)
    
    res := Res{
		Total: total,
		Posts: posts,
	}
    b, _ := json.Marshal(res)
    w.WriteHeader(http.StatusOK)
    w.Write(b)
}

func main() {
    s := &Sample{db}
    h := pagination.Middleware(s)

    http.ListenAndServe(":3000", h)
}


And request with below queries

Key Value Type Desc
sort "["title", "DESC"]" Encoding []string to json Query with ORDER
range "[10, 20]" Encoding []int to json Query with OFFSET and LIMIT
filter "[{"column": "title", "op": "contains", "values": ["abc"]}]" Encoding Filter to json Query with WHERE

For details pagination_test.go

Documentation

Index

Constants

View Source
const (
	FilterOpEqual    = "equal"
	FilterOpContains = "contains"
	FilterOpBetween  = "between"
	FilterOpIn       = "in"
	FilterOpNull     = "null"
	FilterOpNotNull  = "not_null"
)

Variables

View Source
var (
	SortCtxKey   = &contextKey{"sort"}
	OffsetCtxKey = &contextKey{"offset"}
	LimitCtxKey  = &contextKey{"limit"}
	FilterCtxKey = &contextKey{"filter"}
)

Functions

func Middleware

func Middleware(next http.Handler) http.Handler

func PagenateWithContext

func PagenateWithContext(ctx context.Context, db *gorm.DB, total *uint) (*gorm.DB, error)

func Paginate

func Paginate(db *gorm.DB, sort string, offset int, limit int, filters []Filter, total *uint) (*gorm.DB, error)

Types

type Filter

type Filter struct {
	Column string        `json:"column"`
	Op     FilterOp      `json:"op"`
	Values []interface{} `json:"values"`
}

type FilterOp

type FilterOp string

type FilterParam

type FilterParam []Filter

type RangeParam

type RangeParam []int

type SortParam

type SortParam []string

Jump to

Keyboard shortcuts

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