forked from ulule/paging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stores.go
86 lines (69 loc) · 2 KB
/
stores.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package paging
import (
"fmt"
"github.com/jinzhu/gorm"
)
// -----------------------------------------------------------------------------
// Interfaces
// -----------------------------------------------------------------------------
// Store is a store.
type Store interface {
PaginateOffset(limit, offset int64, count *int64) error
PaginateCursor(limit int64, cursor interface{}, fieldName string, reverse bool, hasnext *bool) error
GetItems() interface{}
}
// -----------------------------------------------------------------------------
// GORM Store
// -----------------------------------------------------------------------------
// GORMStore is the store for GORM ORM.
type GORMStore struct {
db *gorm.DB
items interface{}
}
// NewGORMStore returns a new GORM store instance.
func NewGORMStore(db *gorm.DB, items interface{}) (*GORMStore, error) {
return &GORMStore{
db: db,
items: items,
}, nil
}
// GetItems return the current result
func (s *GORMStore) GetItems() interface{} {
return s.items
}
// PaginateOffset paginates items from the store and update page instance.
func (s *GORMStore) PaginateOffset(limit, offset int64, count *int64) error {
q := s.db
q = q.Limit(int(limit))
q = q.Offset(int(offset))
q = q.Find(s.items)
q = q.Limit(-1)
q = q.Offset(-1)
if err := q.Count(count).Error; err != nil {
return err
}
return nil
}
// PaginateCursor paginates items from the store and update page instance for cursor pagination system.
// cursor can be an ID or a date (time.Time)
func (s *GORMStore) PaginateCursor(limit int64, cursor interface{}, fieldName string, reverse bool, hasnext *bool) error {
q := s.db
q = q.Limit(limit + 1)
if reverse {
q = q.Where(fmt.Sprintf("%s < ?", fieldName), cursor)
} else {
q = q.Where(fmt.Sprintf("%s > ?", fieldName), cursor)
}
err := q.Find(s.items).Error
if err != nil {
return err
}
len := getLen(s.items)
if int64(len) <= limit {
*hasnext = false
return nil
}
*hasnext = true
_, s.items = popLastElement(s.items)
return nil
}