forked from shurcooL/graphql
-
Notifications
You must be signed in to change notification settings - Fork 93
/
query.go
353 lines (315 loc) · 10.5 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
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
package graphql
import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
"sort"
"strconv"
"strings"
"github.com/hasura/go-graphql-client/ident"
)
type constructOptionsOutput struct {
operationName string
operationDirectives []string
extensions any
}
func (coo constructOptionsOutput) OperationDirectivesString() string {
operationDirectivesStr := strings.Join(coo.operationDirectives, " ")
if operationDirectivesStr != "" {
return fmt.Sprintf(" %s ", operationDirectivesStr)
}
return ""
}
func constructOptions(options []Option) (*constructOptionsOutput, error) {
output := &constructOptionsOutput{}
for _, option := range options {
switch opt := option.(type) {
case operationNameOption:
output.operationName = opt.name
case bindExtensionsOption:
output.extensions = opt.value
default:
if opt.Type() != OptionTypeOperationDirective {
return nil, fmt.Errorf("invalid query option type: %s", option.Type())
}
if d, ok := option.(fmt.Stringer); ok {
output.operationDirectives = append(output.operationDirectives, d.String())
} else {
return nil, fmt.Errorf("please implement the fmt.Stringer interface for %s option", OptionTypeOperationDirective)
}
}
}
return output, nil
}
func constructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, *constructOptionsOutput, error) {
query, err := query(v)
if err != nil {
return "", nil, err
}
optionsOutput, err := constructOptions(options)
if err != nil {
return "", nil, err
}
if len(variables) > 0 {
return fmt.Sprintf("query %s(%s)%s%s", optionsOutput.operationName, queryArguments(variables), optionsOutput.OperationDirectivesString(), query), optionsOutput, nil
}
if optionsOutput.operationName == "" && len(optionsOutput.operationDirectives) == 0 {
return query, optionsOutput, nil
}
return fmt.Sprintf("query %s%s%s", optionsOutput.operationName, optionsOutput.OperationDirectivesString(), query), optionsOutput, nil
}
// ConstructQuery build GraphQL query string from struct and variables
func ConstructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, error) {
query, _, err := constructQuery(v, variables, options...)
if err != nil {
return "", err
}
return query, err
}
func constructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, *constructOptionsOutput, error) {
query, err := query(v)
if err != nil {
return "", nil, err
}
optionsOutput, err := constructOptions(options)
if err != nil {
return "", nil, err
}
if len(variables) > 0 {
return fmt.Sprintf("mutation %s(%s)%s%s", optionsOutput.operationName, queryArguments(variables), optionsOutput.OperationDirectivesString(), query), optionsOutput, nil
}
if optionsOutput.operationName == "" && len(optionsOutput.operationDirectives) == 0 {
return "mutation" + query, optionsOutput, nil
}
return fmt.Sprintf("mutation %s%s%s", optionsOutput.operationName, optionsOutput.OperationDirectivesString(), query), optionsOutput, nil
}
// ConstructMutation build GraphQL mutation string from struct and variables
func ConstructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, error) {
query, _, err := constructMutation(v, variables, options...)
if err != nil {
return "", err
}
return query, err
}
// ConstructSubscription build GraphQL subscription string from struct and variables
func ConstructSubscription(v interface{}, variables map[string]interface{}, options ...Option) (string, string, error) {
query, err := query(v)
if err != nil {
return "", "", err
}
optionsOutput, err := constructOptions(options)
if err != nil {
return "", "", err
}
if len(variables) > 0 {
return fmt.Sprintf("subscription %s(%s)%s%s", optionsOutput.operationName, queryArguments(variables), optionsOutput.OperationDirectivesString(), query), optionsOutput.operationName, nil
}
if optionsOutput.operationName == "" && len(optionsOutput.operationDirectives) == 0 {
return "subscription" + query, optionsOutput.operationName, nil
}
return fmt.Sprintf("subscription %s%s%s", optionsOutput.operationName, optionsOutput.OperationDirectivesString(), query), optionsOutput.operationName, nil
}
// queryArguments constructs a minified arguments string for variables.
//
// E.g., map[string]interface{}{"a": int(123), "b": true} -> "$a:Int!$b:Boolean!".
func queryArguments(variables map[string]interface{}) string {
// Sort keys in order to produce deterministic output for testing purposes.
// TODO: If tests can be made to work with non-deterministic output, then no need to sort.
keys := make([]string, 0, len(variables))
for k := range variables {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, k := range keys {
_, _ = io.WriteString(&buf, "$")
_, _ = io.WriteString(&buf, k)
_, _ = io.WriteString(&buf, ":")
writeArgumentType(&buf, reflect.TypeOf(variables[k]), variables[k], true)
// Don't insert a comma here.
// Commas in GraphQL are insignificant, and we want minified output.
// See https://facebook.github.io/graphql/October2016/#sec-Insignificant-Commas.
}
return buf.String()
}
// writeArgumentType writes a minified GraphQL type for t to w.
// value indicates whether t is a value (required) type or pointer (optional) type.
// If value is true, then "!" is written at the end of t.
func writeArgumentType(w io.Writer, t reflect.Type, v interface{}, value bool) {
if t.Implements(graphqlTypeInterface) {
var graphqlType GraphQLType
var ok bool
value = t.Kind() != reflect.Ptr
if v != nil {
graphqlType, ok = v.(GraphQLType)
} else if t.Kind() == reflect.Ptr {
graphqlType, ok = reflect.New(t.Elem()).Interface().(GraphQLType)
} else {
graphqlType, ok = reflect.Zero(t).Interface().(GraphQLType)
}
if ok {
_, _ = io.WriteString(w, graphqlType.GetGraphQLType())
if value {
// Value is a required type, so add "!" to the end.
_, _ = io.WriteString(w, "!")
}
return
}
}
if t.Kind() == reflect.Ptr {
// Pointer is an optional type, so no "!" at the end of the pointer's underlying type.
writeArgumentType(w, t.Elem(), v, false)
return
}
switch t.Kind() {
case reflect.Slice, reflect.Array:
// List. E.g., "[Int]".
_, _ = io.WriteString(w, "[")
writeArgumentType(w, t.Elem(), nil, true)
_, _ = io.WriteString(w, "]")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
_, _ = io.WriteString(w, "Int")
case reflect.Float32, reflect.Float64:
_, _ = io.WriteString(w, "Float")
case reflect.Bool:
_, _ = io.WriteString(w, "Boolean")
default:
n := t.Name()
if n == "string" {
n = "String"
}
_, _ = io.WriteString(w, n)
}
if value {
// Value is a required type, so add "!" to the end.
_, _ = io.WriteString(w, "!")
}
}
// query uses writeQuery to recursively construct
// a minified query string from the provided struct v.
//
// E.g., struct{Foo Int, BarBaz *bool} -> "{foo,barBaz}".
func query(v interface{}) (string, error) {
var buf bytes.Buffer
err := writeQuery(&buf, reflect.TypeOf(v), reflect.ValueOf(v), false)
if err != nil {
return "", fmt.Errorf("failed to write query: %w", err)
}
return buf.String(), nil
}
// writeQuery writes a minified query for t to w.
// If inline is true, the struct fields of t are inlined into parent struct.
func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) error {
switch t.Kind() {
case reflect.Ptr:
err := writeQuery(w, t.Elem(), ElemSafe(v), false)
if err != nil {
return fmt.Errorf("failed to write query for ptr `%v`: %w", t, err)
}
case reflect.Struct:
// If the type implements json.Unmarshaler, it's a scalar. Don't expand it.
if reflect.PointerTo(t).Implements(jsonUnmarshaler) {
return nil
}
if t.AssignableTo(idType) {
return nil
}
if !inline {
_, _ = io.WriteString(w, "{")
}
iter := 0
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
value, ok := f.Tag.Lookup("graphql")
// Skip this field if the tag value is hyphen
if value == "-" {
continue
}
if iter != 0 {
_, _ = io.WriteString(w, ",")
}
iter++
inlineField := f.Anonymous && !ok
if !inlineField {
if ok {
_, _ = io.WriteString(w, value)
} else {
_, _ = io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase())
}
}
// Skip writeQuery if the GraphQL type associated with the filed is scalar
if isTrue(f.Tag.Get("scalar")) {
continue
}
err := writeQuery(w, f.Type, FieldSafe(v, i), inlineField)
if err != nil {
return fmt.Errorf("failed to write query for struct field `%v`: %w", f.Name, err)
}
}
if !inline {
_, _ = io.WriteString(w, "}")
}
case reflect.Slice:
if t.Elem().Kind() != reflect.Array {
err := writeQuery(w, t.Elem(), IndexSafe(v, 0), false)
if err != nil {
return fmt.Errorf("failed to write query for slice item `%v`: %w", t, err)
}
return nil
}
// handle [][2]interface{} like an ordered map
if t.Elem().Len() != 2 {
return fmt.Errorf("only arrays of len 2 are supported, got %v", t.Elem())
}
sliceOfPairs := v
_, _ = io.WriteString(w, "{")
for i := 0; i < sliceOfPairs.Len(); i++ {
pair := sliceOfPairs.Index(i)
// it.Value() returns interface{}, so we need to use reflect.ValueOf
// to cast it away
key, val := pair.Index(0), reflect.ValueOf(pair.Index(1).Interface())
keyString, ok := key.Interface().(string)
if !ok {
return fmt.Errorf("expected pair (string, %v), got (%v, %v)",
val.Type(), key.Type(), val.Type())
}
_, _ = io.WriteString(w, keyString)
err := writeQuery(w, val.Type(), val, false)
if err != nil {
return fmt.Errorf("failed to write query for pair[1] `%v`: %w", val.Type(), err)
}
}
_, _ = io.WriteString(w, "}")
case reflect.Map:
return fmt.Errorf("type %v is not supported, use [][2]interface{} instead", t)
}
return nil
}
func IndexSafe(v reflect.Value, i int) reflect.Value {
if v.IsValid() && i < v.Len() {
return v.Index(i)
}
return reflect.ValueOf(nil)
}
func ElemSafe(v reflect.Value) reflect.Value {
if v.IsValid() {
return v.Elem()
}
return reflect.ValueOf(nil)
}
func FieldSafe(valStruct reflect.Value, i int) reflect.Value {
if valStruct.IsValid() {
return valStruct.Field(i)
}
return reflect.ValueOf(nil)
}
var jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
var idType = reflect.TypeOf(ID(""))
var graphqlTypeInterface = reflect.TypeOf((*GraphQLType)(nil)).Elem()
func isTrue(s string) bool {
b, _ := strconv.ParseBool(s)
return b
}