-
Notifications
You must be signed in to change notification settings - Fork 0
/
pagination.go
461 lines (412 loc) · 10.9 KB
/
pagination.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"strconv"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/errcode"
"github.com/google/uuid"
"github.com/minskylab/core/ent/user"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/vmihailenco/msgpack/v5"
)
// OrderDirection defines the directions in which to order a list of items.
type OrderDirection string
const (
// OrderDirectionAsc specifies an ascending order.
OrderDirectionAsc OrderDirection = "ASC"
// OrderDirectionDesc specifies a descending order.
OrderDirectionDesc OrderDirection = "DESC"
)
// Validate the order direction value.
func (o OrderDirection) Validate() error {
if o != OrderDirectionAsc && o != OrderDirectionDesc {
return fmt.Errorf("%s is not a valid OrderDirection", o)
}
return nil
}
// String implements fmt.Stringer interface.
func (o OrderDirection) String() string {
return string(o)
}
// MarshalGQL implements graphql.Marshaler interface.
func (o OrderDirection) MarshalGQL(w io.Writer) {
io.WriteString(w, strconv.Quote(o.String()))
}
// UnmarshalGQL implements graphql.Unmarshaler interface.
func (o *OrderDirection) UnmarshalGQL(val interface{}) error {
str, ok := val.(string)
if !ok {
return fmt.Errorf("order direction %T must be a string", val)
}
*o = OrderDirection(str)
return o.Validate()
}
func (o OrderDirection) reverse() OrderDirection {
if o == OrderDirectionDesc {
return OrderDirectionAsc
}
return OrderDirectionDesc
}
func (o OrderDirection) orderFunc(field string) OrderFunc {
if o == OrderDirectionDesc {
return Desc(field)
}
return Asc(field)
}
func cursorsToPredicates(direction OrderDirection, after, before *Cursor, field, idField string) []func(s *sql.Selector) {
var predicates []func(s *sql.Selector)
if after != nil {
if after.Value != nil {
var predicate func([]string, ...interface{}) *sql.Predicate
if direction == OrderDirectionAsc {
predicate = sql.CompositeGT
} else {
predicate = sql.CompositeLT
}
predicates = append(predicates, func(s *sql.Selector) {
s.Where(predicate(
s.Columns(field, idField),
after.Value, after.ID,
))
})
} else {
var predicate func(string, interface{}) *sql.Predicate
if direction == OrderDirectionAsc {
predicate = sql.GT
} else {
predicate = sql.LT
}
predicates = append(predicates, func(s *sql.Selector) {
s.Where(predicate(
s.C(idField),
after.ID,
))
})
}
}
if before != nil {
if before.Value != nil {
var predicate func([]string, ...interface{}) *sql.Predicate
if direction == OrderDirectionAsc {
predicate = sql.CompositeLT
} else {
predicate = sql.CompositeGT
}
predicates = append(predicates, func(s *sql.Selector) {
s.Where(predicate(
s.Columns(field, idField),
before.Value, before.ID,
))
})
} else {
var predicate func(string, interface{}) *sql.Predicate
if direction == OrderDirectionAsc {
predicate = sql.LT
} else {
predicate = sql.GT
}
predicates = append(predicates, func(s *sql.Selector) {
s.Where(predicate(
s.C(idField),
before.ID,
))
})
}
}
return predicates
}
// PageInfo of a connection type.
type PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
HasPreviousPage bool `json:"hasPreviousPage"`
StartCursor *Cursor `json:"startCursor"`
EndCursor *Cursor `json:"endCursor"`
}
// Cursor of an edge type.
type Cursor struct {
ID uuid.UUID `msgpack:"i"`
Value Value `msgpack:"v,omitempty"`
}
// MarshalGQL implements graphql.Marshaler interface.
func (c Cursor) MarshalGQL(w io.Writer) {
quote := []byte{'"'}
w.Write(quote)
defer w.Write(quote)
wc := base64.NewEncoder(base64.RawStdEncoding, w)
defer wc.Close()
_ = msgpack.NewEncoder(wc).Encode(c)
}
// UnmarshalGQL implements graphql.Unmarshaler interface.
func (c *Cursor) UnmarshalGQL(v interface{}) error {
s, ok := v.(string)
if !ok {
return fmt.Errorf("%T is not a string", v)
}
if err := msgpack.NewDecoder(
base64.NewDecoder(
base64.RawStdEncoding,
strings.NewReader(s),
),
).Decode(c); err != nil {
return fmt.Errorf("cannot decode cursor: %w", err)
}
return nil
}
const errInvalidPagination = "INVALID_PAGINATION"
func validateFirstLast(first, last *int) (err *gqlerror.Error) {
switch {
case first != nil && last != nil:
err = &gqlerror.Error{
Message: "Passing both `first` and `last` to paginate a connection is not supported.",
}
case first != nil && *first < 0:
err = &gqlerror.Error{
Message: "`first` on a connection cannot be less than zero.",
}
errcode.Set(err, errInvalidPagination)
case last != nil && *last < 0:
err = &gqlerror.Error{
Message: "`last` on a connection cannot be less than zero.",
}
errcode.Set(err, errInvalidPagination)
}
return err
}
func getCollectedField(ctx context.Context, path ...string) *graphql.CollectedField {
fc := graphql.GetFieldContext(ctx)
if fc == nil {
return nil
}
oc := graphql.GetOperationContext(ctx)
field := fc.Field
walk:
for _, name := range path {
for _, f := range graphql.CollectFields(oc, field.Selections, nil) {
if f.Name == name {
field = f
continue walk
}
}
return nil
}
return &field
}
func hasCollectedField(ctx context.Context, path ...string) bool {
if graphql.GetFieldContext(ctx) == nil {
return true
}
return getCollectedField(ctx, path...) != nil
}
const (
edgesField = "edges"
nodeField = "node"
pageInfoField = "pageInfo"
totalCountField = "totalCount"
)
// UserEdge is the edge representation of User.
type UserEdge struct {
Node *User `json:"node"`
Cursor Cursor `json:"cursor"`
}
// UserConnection is the connection containing edges to User.
type UserConnection struct {
Edges []*UserEdge `json:"edges"`
PageInfo PageInfo `json:"pageInfo"`
TotalCount int `json:"totalCount"`
}
// UserPaginateOption enables pagination customization.
type UserPaginateOption func(*userPager) error
// WithUserOrder configures pagination ordering.
func WithUserOrder(order *UserOrder) UserPaginateOption {
if order == nil {
order = DefaultUserOrder
}
o := *order
return func(pager *userPager) error {
if err := o.Direction.Validate(); err != nil {
return err
}
if o.Field == nil {
o.Field = DefaultUserOrder.Field
}
pager.order = &o
return nil
}
}
// WithUserFilter configures pagination filter.
func WithUserFilter(filter func(*UserQuery) (*UserQuery, error)) UserPaginateOption {
return func(pager *userPager) error {
if filter == nil {
return errors.New("UserQuery filter cannot be nil")
}
pager.filter = filter
return nil
}
}
type userPager struct {
order *UserOrder
filter func(*UserQuery) (*UserQuery, error)
}
func newUserPager(opts []UserPaginateOption) (*userPager, error) {
pager := &userPager{}
for _, opt := range opts {
if err := opt(pager); err != nil {
return nil, err
}
}
if pager.order == nil {
pager.order = DefaultUserOrder
}
return pager, nil
}
func (p *userPager) applyFilter(query *UserQuery) (*UserQuery, error) {
if p.filter != nil {
return p.filter(query)
}
return query, nil
}
func (p *userPager) toCursor(u *User) Cursor {
return p.order.Field.toCursor(u)
}
func (p *userPager) applyCursors(query *UserQuery, after, before *Cursor) *UserQuery {
for _, predicate := range cursorsToPredicates(
p.order.Direction, after, before,
p.order.Field.field, DefaultUserOrder.Field.field,
) {
query = query.Where(predicate)
}
return query
}
func (p *userPager) applyOrder(query *UserQuery, reverse bool) *UserQuery {
direction := p.order.Direction
if reverse {
direction = direction.reverse()
}
query = query.Order(direction.orderFunc(p.order.Field.field))
if p.order.Field != DefaultUserOrder.Field {
query = query.Order(direction.orderFunc(DefaultUserOrder.Field.field))
}
return query
}
// Paginate executes the query and returns a relay based cursor connection to User.
func (u *UserQuery) Paginate(
ctx context.Context, after *Cursor, first *int,
before *Cursor, last *int, opts ...UserPaginateOption,
) (*UserConnection, error) {
if err := validateFirstLast(first, last); err != nil {
return nil, err
}
pager, err := newUserPager(opts)
if err != nil {
return nil, err
}
if u, err = pager.applyFilter(u); err != nil {
return nil, err
}
conn := &UserConnection{Edges: []*UserEdge{}}
if !hasCollectedField(ctx, edgesField) || first != nil && *first == 0 || last != nil && *last == 0 {
if hasCollectedField(ctx, totalCountField) ||
hasCollectedField(ctx, pageInfoField) {
count, err := u.Count(ctx)
if err != nil {
return nil, err
}
conn.TotalCount = count
conn.PageInfo.HasNextPage = first != nil && count > 0
conn.PageInfo.HasPreviousPage = last != nil && count > 0
}
return conn, nil
}
if (after != nil || first != nil || before != nil || last != nil) && hasCollectedField(ctx, totalCountField) {
count, err := u.Clone().Count(ctx)
if err != nil {
return nil, err
}
conn.TotalCount = count
}
u = pager.applyCursors(u, after, before)
u = pager.applyOrder(u, last != nil)
var limit int
if first != nil {
limit = *first + 1
} else if last != nil {
limit = *last + 1
}
if limit > 0 {
u = u.Limit(limit)
}
if field := getCollectedField(ctx, edgesField, nodeField); field != nil {
u = u.collectField(graphql.GetOperationContext(ctx), *field)
}
nodes, err := u.All(ctx)
if err != nil || len(nodes) == 0 {
return conn, err
}
if len(nodes) == limit {
conn.PageInfo.HasNextPage = first != nil
conn.PageInfo.HasPreviousPage = last != nil
nodes = nodes[:len(nodes)-1]
}
var nodeAt func(int) *User
if last != nil {
n := len(nodes) - 1
nodeAt = func(i int) *User {
return nodes[n-i]
}
} else {
nodeAt = func(i int) *User {
return nodes[i]
}
}
conn.Edges = make([]*UserEdge, len(nodes))
for i := range nodes {
node := nodeAt(i)
conn.Edges[i] = &UserEdge{
Node: node,
Cursor: pager.toCursor(node),
}
}
conn.PageInfo.StartCursor = &conn.Edges[0].Cursor
conn.PageInfo.EndCursor = &conn.Edges[len(conn.Edges)-1].Cursor
if conn.TotalCount == 0 {
conn.TotalCount = len(nodes)
}
return conn, nil
}
// UserOrderField defines the ordering field of User.
type UserOrderField struct {
field string
toCursor func(*User) Cursor
}
// UserOrder defines the ordering of User.
type UserOrder struct {
Direction OrderDirection `json:"direction"`
Field *UserOrderField `json:"field"`
}
// DefaultUserOrder is the default ordering of User.
var DefaultUserOrder = &UserOrder{
Direction: OrderDirectionAsc,
Field: &UserOrderField{
field: user.FieldID,
toCursor: func(u *User) Cursor {
return Cursor{ID: u.ID}
},
},
}
// ToEdge converts User into UserEdge.
func (u *User) ToEdge(order *UserOrder) *UserEdge {
if order == nil {
order = DefaultUserOrder
}
return &UserEdge{
Node: u,
Cursor: order.Field.toCursor(u),
}
}