/
gql_pagination_simple.go
99 lines (90 loc) · 2.5 KB
/
gql_pagination_simple.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
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"strconv"
"github.com/99designs/gqlgen/graphql"
)
var simplePaginationKey = "github.com/woocoos/entco/pkg/ent.SimplePaginzation"
type SimplePagination struct {
CurrentIndex int
PageIndex int
}
// NewSimplePagination creates a new SimplePagination from the given page and count. If both are empty, it returns nil.
func NewSimplePagination(p, c string) (*SimplePagination, error) {
if p == "" && c == "" {
return nil, nil
}
sp := &SimplePagination{}
if p != "" {
i, err := strconv.Atoi(p)
if err != nil {
return nil, err
}
sp.PageIndex = i
}
if c != "" {
i, err := strconv.Atoi(c)
if err != nil {
return nil, err
}
sp.CurrentIndex = i
}
return sp, nil
}
func (u *UserQuery) SimplePaginate(
ctx context.Context, sp *SimplePagination, 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, last != nil)
if err != nil {
return nil, err
}
if u, err = pager.applyFilter(u); err != nil {
return nil, err
}
conn := &UserConnection{Edges: []*UserEdge{}}
ignoredEdges := !hasCollectedField(ctx, edgesField)
if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) {
hasPagination := after != nil || first != nil || before != nil || last != nil
if hasPagination || ignoredEdges {
if conn.TotalCount, err = u.Clone().Count(ctx); err != nil {
return nil, err
}
conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0
conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0
}
}
if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) {
return conn, nil
}
if u, err = pager.applyCursors(u, after, before); err != nil {
return nil, err
}
u = pager.applyOrder(u)
if limit := paginateLimit(first, last); limit != 0 {
u.Limit(limit)
}
if field := collectedField(ctx, edgesField, nodeField); field != nil {
if err := u.collectField(ctx, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil {
return nil, err
}
}
if sp != nil {
if first != nil {
u.Offset((sp.PageIndex - sp.CurrentIndex - 1) * *first)
}
if last != nil {
u.Offset((sp.CurrentIndex - sp.PageIndex - 1) * *last)
}
}
nodes, err := u.All(ctx)
if err != nil {
return nil, err
}
conn.build(nodes, pager, after, first, before, last)
return conn, nil
}