-
Notifications
You must be signed in to change notification settings - Fork 36
/
pagingQuery.go
292 lines (261 loc) · 7.77 KB
/
pagingQuery.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package mongopagination
import (
"context"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Error constants
const (
PageLimitError = "page or limit cannot be less than 0"
DecodeEmptyError = "struct should be provide to decode data"
DecodeNotAvail = "this feature is not available for aggregate query"
FilterInAggregateError = "you cannot use filter in aggregate query but you can pass multiple filter as param in aggregate function"
NilFilterError = "filter query cannot be nil"
)
// PagingQuery struct for holding mongo
// connection, filter needed to apply
// filter data with page, limit, sort key
// and sort value
type pagingQuery struct {
Collection *mongo.Collection
SortFields bson.D
Ctx context.Context
Decoder interface{}
Project interface{}
FilterQuery interface{}
LimitCount int64
PageCount int64
Collation *options.Collation
}
// AutoGenerated is to bind Aggregate query result data
type AutoGenerated struct {
Total []struct {
Count int64 `json:"count"`
} `json:"total"`
Data []bson.Raw `json:"data"`
}
// PagingQuery is an interface that provides list of function
// you can perform on pagingQuery
type PagingQuery interface {
// Find set the filter for query results.
Find() (paginatedData *PaginatedData, err error)
Aggregate(criteria ...interface{}) (paginatedData *PaginatedData, err error)
// Select used to enable fields which should be retrieved.
Select(selector interface{}) PagingQuery
Filter(selector interface{}) PagingQuery
Limit(limit int64) PagingQuery
Page(page int64) PagingQuery
Sort(sortField string, sortValue interface{}) PagingQuery
Decode(decode interface{}) PagingQuery
Context(ctx context.Context) PagingQuery
SetCollation(ctx *options.Collation) PagingQuery
}
// New is to construct PagingQuery object with mongo.Database and collection name
func New(collection *mongo.Collection) PagingQuery {
return &pagingQuery{
Collection: collection,
}
}
// SetCollation is function to set collation for mongo
func (paging *pagingQuery) SetCollation(collation *options.Collation) PagingQuery {
paging.Collation = collation
return paging
}
// Decode is function to decode result data
func (paging *pagingQuery) Decode(decode interface{}) PagingQuery {
paging.Decoder = decode
return paging
}
func (paging *pagingQuery) Context(ctx context.Context) PagingQuery {
paging.Ctx = ctx
return paging
}
// Select helps you to add projection on query
func (paging *pagingQuery) Select(selector interface{}) PagingQuery {
paging.Project = selector
return paging
}
// Filter function is to add filter for mongo query
func (paging *pagingQuery) Filter(criteria interface{}) PagingQuery {
paging.FilterQuery = criteria
return paging
}
// Limit is to add limit for pagination
func (paging *pagingQuery) Limit(limit int64) PagingQuery {
if limit < 1 {
paging.LimitCount = 10
} else {
paging.LimitCount = limit
}
return paging
}
// Page is to specify which page to serve in mongo paginated result
func (paging *pagingQuery) Page(page int64) PagingQuery {
if page < 1 {
paging.PageCount = 1
} else {
paging.PageCount = page
}
return paging
}
// Sort is to sor mongo result by certain key
func (paging *pagingQuery) Sort(sortField string, sortValue interface{}) PagingQuery {
sortQuery := bson.E{}
sortQuery.Key = sortField
sortQuery.Value = sortValue
paging.SortFields = append(paging.SortFields, sortQuery)
return paging
}
// validateQuery query is to check if user has added certain required params or not
func (paging *pagingQuery) validateQuery(isNormal bool) error {
if paging.LimitCount <= 0 || paging.PageCount <= 0 {
return errors.New(PageLimitError)
}
if isNormal && paging.Decoder == nil {
return errors.New(DecodeEmptyError)
}
if !isNormal && paging.Decoder != nil {
return errors.New(DecodeNotAvail)
}
return nil
}
func (paging *pagingQuery) getContext() context.Context {
if paging.Ctx != nil {
return paging.Ctx
} else {
return context.Background()
}
}
// Aggregate help you to paginate mongo pipeline query
// it returns PaginatedData struct and error if any error
// occurs during document query
func (paging *pagingQuery) Aggregate(filters ...interface{}) (paginatedData *PaginatedData, err error) {
// checking if user added required params
if err := paging.validateQuery(false); err != nil {
return nil, err
}
if paging.FilterQuery != nil {
return nil, errors.New(FilterInAggregateError)
}
var aggregationFilter []bson.M
// combining user sent queries
LOOP:
for _, filter := range filters {
switch v := filter.(type) {
case []bson.M:
aggregationFilter = v
break LOOP
default:
aggregationFilter = append(aggregationFilter, filter.(bson.M))
}
}
skip := getSkip(paging.PageCount, paging.LimitCount)
var facetData []bson.M
if len(paging.SortFields) > 0 {
facetData = append(facetData, bson.M{"$sort": paging.SortFields})
}
facetData = append(facetData, bson.M{"$skip": skip})
facetData = append(facetData, bson.M{"$limit": paging.LimitCount})
//if paging.SortField != "" {
// facetData = append(facetData, bson.M{"$sort": bson.M{paging.SortField: paging.SortValue}})
//}
// making facet aggregation pipeline for result and total document count
facet := bson.M{"$facet": bson.M{
"data": facetData,
"total": []bson.M{{"$count": "count"}},
},
}
aggregationFilter = append(aggregationFilter, facet)
diskUse := true
opt := &options.AggregateOptions{
AllowDiskUse: &diskUse,
}
ctx := paging.getContext()
cursor, err := paging.Collection.Aggregate(ctx, aggregationFilter, opt)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
var docs []AutoGenerated
for cursor.Next(ctx) {
var document *AutoGenerated
if err := cursor.Decode(&document); err == nil {
docs = append(docs, *document)
}
}
var data []bson.Raw
var aggCount int64
if len(docs) > 0 && len(docs[0].Data) > 0 {
aggCount = docs[0].Total[0].Count
data = docs[0].Data
}
paginationInfoChan := make(chan *Paginator, 1)
Paging(paging, paginationInfoChan, true, aggCount)
paginationInfo := <-paginationInfoChan
result := PaginatedData{
Pagination: *paginationInfo.PaginationData(),
Data: data,
}
return &result, nil
}
// Find returns two value pagination data with document queried from mongodb and
// error if any error occurs during document query
func (paging *pagingQuery) Find() (paginatedData *PaginatedData, err error) {
if err := paging.validateQuery(true); err != nil {
return nil, err
}
if paging.FilterQuery == nil {
return nil, errors.New(NilFilterError)
}
// get Pagination Info
paginationInfoChan := make(chan *Paginator, 1)
Paging(paging, paginationInfoChan, false, 0)
// set options for sorting and skipping
skip := getSkip(paging.PageCount, paging.LimitCount)
opt := &options.FindOptions{
Skip: &skip,
Limit: &paging.LimitCount,
}
if paging.Project != nil {
opt.SetProjection(paging.Project)
}
if len(paging.SortFields) > 0 {
opt.SetSort(paging.SortFields)
}
if paging.Collation != nil {
opt.SetCollation(paging.Collation)
}
ctx := paging.getContext()
cursor, err := paging.Collection.Find(ctx, paging.FilterQuery, opt)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
docs := paging.Decoder
err = cursor.All(ctx, docs)
if err != nil {
return nil, err
}
paginationInfo := <-paginationInfoChan
result := PaginatedData{
Pagination: *paginationInfo.PaginationData(),
}
return &result, nil
}
// PaginatedData struct holds data and
// pagination detail
type PaginatedData struct {
Data []bson.Raw `json:"data"`
Pagination PaginationData `json:"pagination"`
}
// getSkip return calculated skip value for query
func getSkip(page, limit int64) int64 {
page--
skip := page * limit
if skip <= 0 {
skip = 0
}
return skip
}