-
Notifications
You must be signed in to change notification settings - Fork 2
/
query.go
265 lines (233 loc) · 7.15 KB
/
query.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
package unigraphclient
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/emersonmacro/go-uniswap-subgraph-client/graphql"
)
func constructByIdQuery(id string, model modelFields, opts *RequestOptions) (*graphql.Request, error) {
if opts == nil {
opts = &RequestOptions{
IncludeFields: []string{"*"},
}
}
err := validateRequestOpts(ById, opts)
if err != nil {
return nil, err
}
if slices.Contains(opts.IncludeFields, "*") {
fields, err := gatherModelFields(model, opts.ExcludeFields, true)
if err != nil {
return nil, err
}
opts.IncludeFields = fields
}
query, err := assembleQuery(ById, model, opts)
if err != nil {
return nil, err
}
req := graphql.NewRequest(query)
req.Var("id", id)
fmt.Println("*** DEBUG req.Query() ***")
fmt.Println(req.Query())
fmt.Println("*************")
return req, nil
}
func constructListQuery(model modelFields, opts *RequestOptions) (*graphql.Request, error) {
if opts == nil {
opts = &RequestOptions{
IncludeFields: []string{"*"},
}
}
err := validateRequestOpts(List, opts)
if err != nil {
return nil, err
}
if slices.Contains(opts.IncludeFields, "*") {
fields, err := gatherModelFields(model, opts.ExcludeFields, true)
if err != nil {
return nil, err
}
opts.IncludeFields = fields
}
query, err := assembleQuery(List, model, opts)
if err != nil {
return nil, err
}
req := graphql.NewRequest(query)
req.Var("first", opts.First)
req.Var("skip", opts.Skip)
req.Var("orderBy", opts.OrderBy)
req.Var("orderDir", opts.OrderDir)
fmt.Println("*** DEBUG req.Query() ***")
fmt.Println(req.Query())
fmt.Println("*************")
return req, nil
}
// assembles a properly formatted graphql query based on the provided includeFields
func assembleQuery(queryType QueryType, model modelFields, opts *RequestOptions) (string, error) {
var parts []string
var blockSubstr string = ""
if opts.Block != 0 {
blockSubstr = fmt.Sprintf(", block: {number: %d}", opts.Block)
}
switch queryType {
case ById:
parts = []string{
fmt.Sprintf("query %s($id: ID!) {", model.name),
fmt.Sprintf(" %s(id: $id%s) {", model.name, blockSubstr),
}
case List:
parts = []string{
fmt.Sprintf("query %s($first: Int!, $skip: Int!, $orderBy: String!, $orderDir: String!) {", pluralizeModelName(model.name)),
fmt.Sprintf(" %s(first: $first, skip: $skip, orderBy: $orderBy, orderDirection: $orderDir%s) {", pluralizeModelName(model.name), blockSubstr),
}
default:
return "", fmt.Errorf("unrecognized query type (%v)", queryType)
}
var refFieldMap map[string]fieldRefs = make(map[string]fieldRefs)
// TODO: think about ways to make the rest of this function more comprehensible
for _, field := range opts.IncludeFields {
isRef := false
for k, v := range model.reference {
prefix := fmt.Sprintf("%s.", k)
if strings.HasPrefix(field, prefix) {
isRef = true
refModel, ok := modelMap[v]
if !ok {
return "", fmt.Errorf("reference field not found (%s)", k)
}
fieldWithoutPrefix := cutPrefix(field, prefix)
fieldRef := refFieldMap[k]
if strings.Contains(fieldWithoutPrefix, ".") {
subRefFields := strings.Split(fieldWithoutPrefix, ".")
subRefModel, ok := modelMap[refModel.reference[subRefFields[0]]]
if !ok {
return "", fmt.Errorf("sub-reference field not found (%s)", fieldWithoutPrefix)
}
if !validateField(subRefModel, subRefFields[1]) {
return "", fmt.Errorf("unrecognized field given in opts.IncludeFields (%s)", field)
}
fieldRef.refs = append(fieldRef.refs, fieldWithoutPrefix)
} else {
if !validateField(refModel, fieldWithoutPrefix) {
return "", fmt.Errorf("unrecognized field given in opts.IncludeFields (%s)", field)
}
fieldRef.directs = append(fieldRef.directs, fieldWithoutPrefix)
}
refFieldMap[k] = fieldRef
break
}
}
if !isRef {
if !validateField(model, field) {
return "", fmt.Errorf("unrecognized field given in opts.IncludeFields (%s)", field)
}
parts = append(parts, fmt.Sprintf(" %s", field))
}
}
for k, v := range refFieldMap {
parts = append(parts, fmt.Sprintf(" %s {", k))
if len(v.directs) > 0 {
parts = append(parts, " "+strings.Join(v.directs, "\n "))
}
subRefMap := make(map[string][]string)
for _, ref := range v.refs {
fieldSplit := strings.Split(ref, ".")
if len(fieldSplit) < 2 {
return "", fmt.Errorf("error parsing reference field (%s)", ref)
}
parent := fieldSplit[0]
child := fieldSplit[1]
subRefMap[parent] = append(subRefMap[parent], child)
}
for subK, subV := range subRefMap {
parts = append(parts, fmt.Sprintf(" %s {", subK), " "+strings.Join(subV, "\n "), " }")
}
parts = append(parts, " }")
}
parts = append(parts, " }", "}")
query := strings.Join(parts, "\n")
return query, nil
}
// recursively gathers all fields for the given model, while honoring fields to be excluded
func gatherModelFields(model modelFields, excludeFields []string, populateRefs bool) ([]string, error) {
fields := []string{}
for _, field := range model.direct {
if !slices.Contains(excludeFields, field) {
fields = append(fields, field)
}
}
for k, v := range model.reference {
if populateRefs {
refModel, ok := modelMap[v]
if !ok {
return nil, fmt.Errorf("reference field not found (%s)", k)
}
refFields, err := gatherModelFields(refModel, excludeFields, false)
if err != nil {
return nil, err
}
for _, refField := range refFields {
fullRef := fmt.Sprintf("%s.%s", k, refField)
if !slices.Contains(excludeFields, fullRef) {
fields = append(fields, fullRef)
}
}
} else {
refWithId := fmt.Sprintf("%s.id", k)
if !slices.Contains(excludeFields, refWithId) {
fields = append(fields, refWithId)
}
}
}
return fields, nil
}
func validateField(model modelFields, field string) bool {
return slices.Contains(model.direct, field)
}
func cutPrefix(s string, prefix string) string {
cut, _ := strings.CutPrefix(s, prefix)
return cut
}
func validateRequestOpts(queryType QueryType, opts *RequestOptions) error {
if len(opts.IncludeFields) == 0 {
opts.IncludeFields = []string{"*"}
}
if !slices.Contains(opts.IncludeFields, "*") && len(opts.ExcludeFields) > 0 {
return errors.New("request options error: ExcludeFields can only be provided when IncludeFields is set to '*'")
}
switch queryType {
case ById:
if opts.First != 0 || opts.Skip != 0 || opts.OrderBy != "" || opts.OrderDir != "" {
return errors.New("request options error: List query options (First, Skip, OrderBy, OrderDir) should not be provided for ById queries")
}
case List:
if opts.First > 1000 {
return errors.New("request options error: First is too large (must be <= 1000)")
}
if opts.First == 0 {
opts.First = 100
}
if opts.OrderBy == "" {
opts.OrderBy = "id"
}
if opts.OrderDir == "" {
opts.OrderDir = "asc"
}
if opts.OrderDir != "asc" && opts.OrderDir != "desc" {
return errors.New("request options error: 'asc' and 'desc' are the only valid options for OrderDir")
}
}
return nil
}
func pluralizeModelName(name string) string {
if name == "factory" {
return "factories"
}
if name == "flash" {
return "flashes"
}
return fmt.Sprintf("%ss", name)
}