-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpagination.go
106 lines (92 loc) · 2.5 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
package pagination
import (
"github.com/graphql-go/graphql"
)
type Page struct {
Skip int
Limit int
}
type PaginatedField struct {
Name string `json:"name"`
Type graphql.Output `json:"type"`
Args graphql.FieldConfigArgument `json:"args"`
DataResolve PaginatedResolverFn `json:"-"`
CountResolve PaginatedResolverFn `json:"-"`
DataAndCountResolve PaginatedDataCountResolverFn `json:"-"`
DeprecationReason string `json:"deprecationReason"`
Description string `json:"description"`
}
type PaginatedResult struct {
Data interface{} `json:"data"`
Count int `json:"count"`
}
type PaginatedResolverFn func(params graphql.ResolveParams, page Page) (interface{}, error)
type PaginatedDataCountResolverFn func(params graphql.ResolveParams, page Page) (interface{}, int, error)
func Paginated(f *PaginatedField) *graphql.Field {
gqlType := graphql.NewObject(graphql.ObjectConfig{
Name: f.Name,
Fields: graphql.Fields{
"data": &graphql.Field{
Type: graphql.NewList(f.Type),
},
"count": &graphql.Field{
Type: graphql.Int,
},
},
})
if f.Args == nil {
f.Args = graphql.FieldConfigArgument{}
}
args := f.Args
args["skip"] = &graphql.ArgumentConfig{
Type: graphql.Int,
Description: "Pagination Skip",
DefaultValue: 0,
}
args["limit"] = &graphql.ArgumentConfig{
Type: graphql.Int,
Description: "Pagination Limit",
DefaultValue: 10,
}
return &graphql.Field{
Name: f.Name,
Type: gqlType,
Args: f.Args,
Resolve: func(p graphql.ResolveParams) (i interface{}, e error) {
fields := GetSelectedGraphQLQueryFields(p)
withData := StringSliceContains(fields, "data")
withCount := StringSliceContains(fields, "count")
r := &PaginatedResult{}
page := Page{
Limit: p.Args["limit"].(int),
Skip: p.Args["skip"].(int),
}
if f.DataAndCountResolve != nil {
data, count, err := f.DataAndCountResolve(p, page)
if err != nil {
return nil, err
}
r.Data = data
r.Count = count
return r, nil
}
if withData {
data, err := f.DataResolve(p, page)
if err != nil {
return nil, err
}
r.Data = data
}
if withCount {
count, err := f.CountResolve(p, page)
if err != nil {
return nil, err
}
r.Count = count.(int)
}
return r, nil
},
DeprecationReason: f.DeprecationReason,
Description: f.Description,
}
}