forked from graphql-go/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
values.go
469 lines (432 loc) · 12.1 KB
/
values.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package graphql
import (
"encoding/json"
"fmt"
"math"
"reflect"
"strings"
"github.com/ahmadmuzakki/graphql/gqlerrors"
"github.com/ahmadmuzakki/graphql/language/ast"
"github.com/ahmadmuzakki/graphql/language/kinds"
"github.com/ahmadmuzakki/graphql/language/printer"
"sort"
)
// Prepares an object map of variableValues of the correct type based on the
// provided variable definitions and arbitrary input. If the input cannot be
// parsed to match the variable definitions, a GraphQLError will be returned.
func getVariableValues(schema Schema, definitionASTs []*ast.VariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) {
values := map[string]interface{}{}
for _, defAST := range definitionASTs {
if defAST == nil || defAST.Variable == nil || defAST.Variable.Name == nil {
continue
}
varName := defAST.Variable.Name.Value
varValue, err := getVariableValue(schema, defAST, inputs[varName])
if err != nil {
return values, err
}
values[varName] = varValue
}
return values, nil
}
// Prepares an object map of argument values given a list of argument
// definitions and list of argument AST nodes.
func getArgumentValues(argDefs []*Argument, argASTs []*ast.Argument, variableVariables map[string]interface{}) (map[string]interface{}, error) {
argASTMap := map[string]*ast.Argument{}
for _, argAST := range argASTs {
if argAST.Name != nil {
argASTMap[argAST.Name.Value] = argAST
}
}
results := map[string]interface{}{}
for _, argDef := range argDefs {
name := argDef.PrivateName
var valueAST ast.Value
if argAST, ok := argASTMap[name]; ok {
valueAST = argAST.Value
}
value := valueFromAST(valueAST, argDef.Type, variableVariables)
if isNullish(value) {
value = argDef.DefaultValue
}
if !isNullish(value) {
results[name] = value
}
}
return results, nil
}
// Given a variable definition, and any value of input, return a value which
// adheres to the variable definition, or throw an error.
func getVariableValue(schema Schema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) {
ttype, err := typeFromAST(schema, definitionAST.Type)
if err != nil {
return nil, err
}
variable := definitionAST.Variable
if ttype == nil || !IsInputType(ttype) {
return "", gqlerrors.NewError(
fmt.Sprintf(`Variable "$%v" expected value of type `+
`"%v" which cannot be used as an input type.`, variable.Name.Value, printer.Print(definitionAST.Type)),
[]ast.Node{definitionAST},
"",
nil,
[]int{},
nil,
)
}
isValid, messages := isValidInputValue(input, ttype)
if isValid {
if isNullish(input) {
defaultValue := definitionAST.DefaultValue
if defaultValue != nil {
variables := map[string]interface{}{}
val := valueFromAST(defaultValue, ttype, variables)
return val, nil
}
}
return coerceValue(ttype, input), nil
}
if isNullish(input) {
return "", gqlerrors.NewError(
fmt.Sprintf(`Variable "$%v" of required type `+
`"%v" was not provided.`, variable.Name.Value, printer.Print(definitionAST.Type)),
[]ast.Node{definitionAST},
"",
nil,
[]int{},
nil,
)
}
// convert input interface into string for error message
inputStr := ""
b, err := json.Marshal(input)
if err == nil {
inputStr = string(b)
}
messagesStr := ""
if len(messages) > 0 {
messagesStr = "\n" + strings.Join(messages, "\n")
}
return "", gqlerrors.NewError(
fmt.Sprintf(`Variable "$%v" got invalid value `+
`%v.%v`, variable.Name.Value, inputStr, messagesStr),
[]ast.Node{definitionAST},
"",
nil,
[]int{},
nil,
)
}
// Given a type and any value, return a runtime value coerced to match the type.
func coerceValue(ttype Input, value interface{}) interface{} {
if ttype, ok := ttype.(*NonNull); ok {
return coerceValue(ttype.OfType, value)
}
if isNullish(value) {
return nil
}
if ttype, ok := ttype.(*List); ok {
itemType := ttype.OfType
valType := reflect.ValueOf(value)
if valType.Kind() == reflect.Slice {
values := []interface{}{}
for i := 0; i < valType.Len(); i++ {
val := valType.Index(i).Interface()
v := coerceValue(itemType, val)
values = append(values, v)
}
return values
}
val := coerceValue(itemType, value)
return []interface{}{val}
}
if ttype, ok := ttype.(*InputObject); ok {
valueMap, ok := value.(map[string]interface{})
if !ok {
valueMap = map[string]interface{}{}
}
obj := map[string]interface{}{}
for fieldName, field := range ttype.Fields() {
value, _ := valueMap[fieldName]
fieldValue := coerceValue(field.Type, value)
if isNullish(fieldValue) {
fieldValue = field.DefaultValue
}
if !isNullish(fieldValue) {
obj[fieldName] = fieldValue
}
}
return obj
}
switch ttype := ttype.(type) {
case *Scalar:
parsed := ttype.ParseValue(value)
if !isNullish(parsed) {
return parsed
}
case *Enum:
parsed := ttype.ParseValue(value)
if !isNullish(parsed) {
return parsed
}
}
return nil
}
// graphql-js/src/utilities.js`
// TODO: figure out where to organize utils
// TODO: change to *Schema
func typeFromAST(schema Schema, inputTypeAST ast.Type) (Type, error) {
switch inputTypeAST := inputTypeAST.(type) {
case *ast.List:
innerType, err := typeFromAST(schema, inputTypeAST.Type)
if err != nil {
return nil, err
}
return NewList(innerType), nil
case *ast.NonNull:
innerType, err := typeFromAST(schema, inputTypeAST.Type)
if err != nil {
return nil, err
}
return NewNonNull(innerType), nil
case *ast.Named:
nameValue := ""
if inputTypeAST.Name != nil {
nameValue = inputTypeAST.Name.Value
}
ttype := schema.Type(nameValue)
return ttype, nil
default:
return nil, invariant(inputTypeAST.GetKind() == kinds.Named, "Must be a named type.")
}
}
// isValidInputValue alias isValidJSValue
// Given a value and a GraphQL type, determine if the value will be
// accepted for that type. This is primarily useful for validating the
// runtime values of query variables.
func isValidInputValue(value interface{}, ttype Input) (bool, []string) {
if ttype, ok := ttype.(*NonNull); ok {
if isNullish(value) {
if ttype.OfType.Name() != "" {
return false, []string{fmt.Sprintf(`Expected "%v!", found null.`, ttype.OfType.Name())}
}
return false, []string{"Expected non-null value, found null."}
}
return isValidInputValue(value, ttype.OfType)
}
if isNullish(value) {
return true, nil
}
switch ttype := ttype.(type) {
case *List:
itemType := ttype.OfType
valType := reflect.ValueOf(value)
if valType.Kind() == reflect.Ptr {
valType = valType.Elem()
}
if valType.Kind() == reflect.Slice {
messagesReduce := []string{}
for i := 0; i < valType.Len(); i++ {
val := valType.Index(i).Interface()
_, messages := isValidInputValue(val, itemType)
for idx, message := range messages {
messagesReduce = append(messagesReduce, fmt.Sprintf(`In element #%v: %v`, idx+1, message))
}
}
return (len(messagesReduce) == 0), messagesReduce
}
return isValidInputValue(value, itemType)
case *InputObject:
messagesReduce := []string{}
valueMap, ok := value.(map[string]interface{})
if !ok {
return false, []string{fmt.Sprintf(`Expected "%v", found not an object.`, ttype.Name())}
}
fields := ttype.Fields()
// to ensure stable order of field evaluation
fieldNames := []string{}
valueMapFieldNames := []string{}
for fieldName := range fields {
fieldNames = append(fieldNames, fieldName)
}
sort.Strings(fieldNames)
for fieldName := range valueMap {
valueMapFieldNames = append(valueMapFieldNames, fieldName)
}
sort.Strings(valueMapFieldNames)
// Ensure every provided field is defined.
for _, fieldName := range valueMapFieldNames {
if _, ok := fields[fieldName]; !ok {
messagesReduce = append(messagesReduce, fmt.Sprintf(`In field "%v": Unknown field.`, fieldName))
}
}
// Ensure every defined field is valid.
for _, fieldName := range fieldNames {
_, messages := isValidInputValue(valueMap[fieldName], fields[fieldName].Type)
if messages != nil {
for _, message := range messages {
messagesReduce = append(messagesReduce, fmt.Sprintf(`In field "%v": %v`, fieldName, message))
}
}
}
return (len(messagesReduce) == 0), messagesReduce
}
switch ttype := ttype.(type) {
case *Scalar:
parsedVal := ttype.ParseValue(value)
if isNullish(parsedVal) {
return false, []string{fmt.Sprintf(`Expected type "%v", found "%v".`, ttype.Name(), value)}
}
return true, nil
case *Enum:
parsedVal := ttype.ParseValue(value)
if isNullish(parsedVal) {
return false, []string{fmt.Sprintf(`Expected type "%v", found "%v".`, ttype.Name(), value)}
}
return true, nil
}
return true, nil
}
// Returns true if a value is null, undefined, or NaN.
func isNullish(value interface{}) bool {
if value, ok := value.(*string); ok {
if value == nil {
return true
}
return *value == ""
}
if value, ok := value.(int); ok {
return math.IsNaN(float64(value))
}
if value, ok := value.(*int); ok {
if value == nil {
return true
}
return math.IsNaN(float64(*value))
}
if value, ok := value.(float32); ok {
return math.IsNaN(float64(value))
}
if value, ok := value.(*float32); ok {
if value == nil {
return true
}
return math.IsNaN(float64(*value))
}
if value, ok := value.(float64); ok {
return math.IsNaN(value)
}
if value, ok := value.(*float64); ok {
if value == nil {
return true
}
return math.IsNaN(*value)
}
return value == nil
}
/**
* Produces a value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String / Enum Value | String |
* | Int / Float | Number |
*
*/
func valueFromAST(valueAST ast.Value, ttype Input, variables map[string]interface{}) interface{} {
if ttype, ok := ttype.(*NonNull); ok {
val := valueFromAST(valueAST, ttype.OfType, variables)
return val
}
if valueAST == nil {
return nil
}
if valueAST, ok := valueAST.(*ast.Variable); ok && valueAST.Kind == kinds.Variable {
if valueAST.Name == nil {
return nil
}
if variables == nil {
return nil
}
variableName := valueAST.Name.Value
variableVal, ok := variables[variableName]
if !ok {
return nil
}
// Note: we're not doing any checking that this variable is correct. We're
// assuming that this query has been validated and the variable usage here
// is of the correct type.
return variableVal
}
if ttype, ok := ttype.(*List); ok {
itemType := ttype.OfType
if valueAST, ok := valueAST.(*ast.ListValue); ok && valueAST.Kind == kinds.ListValue {
values := []interface{}{}
for _, itemAST := range valueAST.Values {
v := valueFromAST(itemAST, itemType, variables)
values = append(values, v)
}
return values
}
v := valueFromAST(valueAST, itemType, variables)
return []interface{}{v}
}
if ttype, ok := ttype.(*InputObject); ok {
valueAST, ok := valueAST.(*ast.ObjectValue)
if !ok {
return nil
}
fieldASTs := map[string]*ast.ObjectField{}
for _, fieldAST := range valueAST.Fields {
if fieldAST.Name == nil {
continue
}
fieldName := fieldAST.Name.Value
fieldASTs[fieldName] = fieldAST
}
obj := map[string]interface{}{}
for fieldName, field := range ttype.Fields() {
fieldAST, ok := fieldASTs[fieldName]
fieldValue := field.DefaultValue
if !ok || fieldAST == nil {
if fieldValue == nil {
continue
}
} else {
fieldValue = valueFromAST(fieldAST.Value, field.Type, variables)
}
if isNullish(fieldValue) {
fieldValue = field.DefaultValue
}
if !isNullish(fieldValue) {
obj[fieldName] = fieldValue
}
}
return obj
}
switch ttype := ttype.(type) {
case *Scalar:
parsed := ttype.ParseLiteral(valueAST)
if !isNullish(parsed) {
return parsed
}
case *Enum:
parsed := ttype.ParseLiteral(valueAST)
if !isNullish(parsed) {
return parsed
}
}
return nil
}
func invariant(condition bool, message string) error {
if !condition {
return gqlerrors.NewFormattedError(message)
}
return nil
}