@@ -10,24 +10,41 @@ import (
1010var Pagination paginator.Paginator
1111
1212type PaginationMeta struct {
13- CurrentPage int `json:"current_page"`
14- PerPage int `json:"per_page"`
15- LastPage int `json:"last_page"`
16- Total int `json:"total"`
13+ CurrentPage int `json:"current_page"`
14+ PerPage int `json:"per_page"`
15+ LastPage int `json:"last_page"`
16+ Total int64 `json:"total"`
1717}
1818
1919type Paginator struct {
2020 Meta PaginationMeta `json:"meta"`
21+ db * gorm.DB
2122 * paginator.Paginator
23+ model interface {}
24+ filter map [string ]interface {}
2225}
2326
24- func (paginator * Paginator ) PaginateScope () func (db * gorm.DB ) * gorm.DB {
27+ func (paginator * Paginator ) PaginateScope (page int , limit int ) func (db * gorm.DB ) * gorm.DB {
28+ if page == 0 {
29+ page = 1
30+ }
31+ if limit == 0 {
32+ limit = 10
33+ }
34+ var totalRows int64
35+
36+ paginator .Meta .CurrentPage = page
37+ paginator .Meta .PerPage = limit
38+
39+ DB .Model (paginator .model ).Where (paginator .filter ).Count (& totalRows )
40+ paginator .Meta .Total = totalRows
41+ paginator .Meta .LastPage = int (math .Ceil (float64 (totalRows ) / float64 (limit )))
42+
2543 return func (db * gorm.DB ) * gorm.DB {
2644 offset := (paginator .Meta .CurrentPage - 1 ) * paginator .Meta .PerPage
2745 return db .Offset (offset ).Limit (paginator .Meta .PerPage )
2846 }
2947}
30-
3148func (paginator * Paginator ) CursorPaginate (query * gorm.DB , v interface {}) (* gorm.DB , paginator.Cursor , error ) {
3249 return paginator .Paginate (query , v )
3350}
@@ -57,11 +74,11 @@ func (paginator *Paginator) updateMeta(v interface{}, request map[string]interfa
5774
5875 var totalRows int64
5976 DB .Model (v ).Count (& totalRows )
60- paginator .Meta .Total = int ( totalRows )
77+ paginator .Meta .Total = totalRows
6178 paginator .Meta .LastPage = int (math .Ceil (float64 (totalRows ) / float64 (limit )))
6279}
6380
64- func NewPaginator (v interface {}, request map [string ]interface {}) * Paginator {
81+ func NewPaginator (v interface {}, queryFilter map [string ]interface {}) * Paginator {
6582 opts := []paginator.Option {
6683 & paginator.Config {
6784 Order : paginator .ASC ,
@@ -70,8 +87,6 @@ func NewPaginator(v interface{}, request map[string]interface{}) *Paginator {
7087
7188 p := paginator .New (opts ... )
7289
73- newInstance := & Paginator {Meta : PaginationMeta {}, Paginator : p }
74- newInstance .updateMeta (v , request )
75-
90+ newInstance := & Paginator {Meta : PaginationMeta {}, Paginator : p , model : v , filter : queryFilter }
7691 return newInstance
7792}
0 commit comments