-
Notifications
You must be signed in to change notification settings - Fork 0
/
pagination.go
227 lines (195 loc) · 5.71 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
package relay
import (
"context"
"github.com/pkg/errors"
"github.com/samber/lo"
)
type OrderBy struct {
Field string `json:"field"`
Desc bool `json:"desc"`
}
type PaginateRequest[T any] struct {
After *string `json:"after"`
First *int `json:"first"`
Before *string `json:"before"`
Last *int `json:"last"`
OrderBys []OrderBy `json:"orderBys"`
}
type Edge[T any] struct {
Node T `json:"node"`
Cursor string `json:"cursor"`
}
type PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
HasPreviousPage bool `json:"hasPreviousPage"`
StartCursor *string `json:"startCursor"`
EndCursor *string `json:"endCursor"`
}
type Connection[T any] struct {
Edges []*Edge[T] `json:"edges,omitempty"`
Nodes []T `json:"nodes,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
TotalCount *int `json:"totalCount,omitempty"`
}
type ApplyCursorsRequest struct {
Before *string
After *string
OrderBys []OrderBy
Limit int
FromEnd bool
}
type LazyEdge[T any] struct {
Node T
Cursor func(ctx context.Context, node T) (string, error)
}
type ApplyCursorsResponse[T any] struct {
LazyEdges []*LazyEdge[T]
TotalCount *int
HasBeforeOrNext bool // `before` exists or it's next exists
HasAfterOrPrevious bool // `after` exists or it's previous exists
}
// https://relay.dev/graphql/connections.htm#ApplyCursorsToEdges()
type ApplyCursorsFunc[T any] func(ctx context.Context, req *ApplyCursorsRequest) (*ApplyCursorsResponse[T], error)
// https://relay.dev/graphql/connections.htm#sec-Pagination-algorithm
// https://relay.dev/graphql/connections.htm#sec-undefined.PageInfo.Fields
func paginate[T any](ctx context.Context, req *PaginateRequest[T], applyCursorsFunc ApplyCursorsFunc[T]) (*Connection[T], error) {
if req.First == nil && req.Last == nil {
return nil, errors.New("first or last must be set")
}
if req.First != nil && req.Last != nil {
return nil, errors.New("first and last cannot be used together")
}
if req.First != nil && *req.First < 0 {
return nil, errors.New("first must be a non-negative integer")
}
if req.Last != nil && *req.Last < 0 {
return nil, errors.New("last must be a non-negative integer")
}
orderBys := req.OrderBys
if len(orderBys) > 0 {
dups := lo.FindDuplicatesBy(orderBys, func(item OrderBy) string {
return item.Field
})
if len(dups) > 0 {
return nil, errors.Errorf("duplicated order by fields %v", lo.Map(dups, func(item OrderBy, _ int) string {
return item.Field
}))
}
}
skip := GetSkip(ctx)
if skip.All() {
return &Connection[T]{}, nil
}
var limit int
if req.First != nil {
limit = *req.First + 1
} else {
limit = *req.Last + 1
}
rsp, err := applyCursorsFunc(ctx, &ApplyCursorsRequest{
Before: req.Before,
After: req.After,
OrderBys: orderBys,
Limit: limit,
FromEnd: req.Last != nil,
})
if err != nil {
return nil, err
}
lazyEdges := rsp.LazyEdges
processor := GetNodeProcessor[T](ctx)
if processor != nil {
for _, lazyEdge := range lazyEdges {
node, err := processor(ctx, lazyEdge.Node)
if err != nil {
return nil, err
}
lazyEdge.Node = node
}
}
var hasPreviousPage, hasNextPage bool
if req.First != nil && len(lazyEdges) > *req.First {
lazyEdges = lazyEdges[:*req.First]
hasNextPage = true
}
if req.Before != nil && rsp.HasBeforeOrNext {
hasNextPage = true
}
if req.Last != nil && len(lazyEdges) > *req.Last {
lazyEdges = lazyEdges[len(lazyEdges)-*req.Last:]
hasPreviousPage = true
}
if req.After != nil && rsp.HasAfterOrPrevious {
hasPreviousPage = true
}
conn := &Connection[T]{}
if !skip.Edges {
edges := make([]*Edge[T], len(lazyEdges))
for i, lazyEdge := range lazyEdges {
cursor, err := lazyEdge.Cursor(ctx, lazyEdge.Node)
if err != nil {
return nil, err
}
edges[i] = &Edge[T]{Node: lazyEdge.Node, Cursor: cursor}
}
conn.Edges = edges
}
if !skip.Nodes {
nodes := make([]T, len(lazyEdges))
for i, lazyEdge := range lazyEdges {
nodes[i] = lazyEdge.Node
}
conn.Nodes = nodes
}
if !skip.TotalCount {
conn.TotalCount = rsp.TotalCount
}
if !skip.PageInfo {
pageInfo := &PageInfo{
HasNextPage: hasNextPage,
HasPreviousPage: hasPreviousPage,
}
if len(lazyEdges) > 0 {
var startCursor, endCursor string
if len(conn.Edges) > 0 {
startCursor = conn.Edges[0].Cursor
endCursor = conn.Edges[len(conn.Edges)-1].Cursor
} else {
startCursor, err = lazyEdges[0].Cursor(ctx, lazyEdges[0].Node)
if err != nil {
return nil, err
}
endIndex := len(lazyEdges) - 1
if endIndex == 0 {
endCursor = startCursor
} else {
endCursor, err = lazyEdges[endIndex].Cursor(ctx, lazyEdges[endIndex].Node)
if err != nil {
return nil, err
}
}
}
pageInfo.StartCursor = &startCursor
pageInfo.EndCursor = &endCursor
}
conn.PageInfo = pageInfo
}
return conn, nil
}
type Pagination[T any] interface {
Paginate(ctx context.Context, req *PaginateRequest[T]) (*Connection[T], error)
}
type PaginationFunc[T any] func(ctx context.Context, req *PaginateRequest[T]) (*Connection[T], error)
func (f PaginationFunc[T]) Paginate(ctx context.Context, req *PaginateRequest[T]) (*Connection[T], error) {
return f(ctx, req)
}
func New[T any](applyCursorsFunc ApplyCursorsFunc[T], middlewares ...PaginationMiddleware[T]) Pagination[T] {
if applyCursorsFunc == nil {
panic("applyCursorsFunc must be set")
}
var p Pagination[T] = PaginationFunc[T](func(ctx context.Context, req *PaginateRequest[T]) (*Connection[T], error) {
cursorMiddlewares := CursorMiddlewaresFromContext[T](ctx)
return paginate(ctx, req, chainCursorMiddlewares(cursorMiddlewares)(applyCursorsFunc))
})
return chainPaginationMiddlewares(middlewares)(p)
}