Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix issue #160: validateVarType parsing numbers #216

Merged
merged 2 commits into from
Apr 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions validator/vars.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package validator

import (
"encoding/json"
"fmt"
"reflect"
"strconv"
Expand Down Expand Up @@ -29,6 +30,7 @@ func VariableValues(schema *ast.Schema, op *ast.OperationDefinition, variables m
}

val, hasValue := variables[v.Variable]

if !hasValue {
if v.DefaultValue != nil {
var err error
Expand All @@ -50,6 +52,24 @@ func VariableValues(schema *ast.Schema, op *ast.OperationDefinition, variables m
coercedVars[v.Variable] = nil
} else {
rv := reflect.ValueOf(val)

jsonNumber, isJsonNumber := val.(json.Number)
if isJsonNumber {
if v.Type.NamedType == "Int" {
n, err := jsonNumber.Int64()
if err != nil {
return nil, gqlerror.ErrorPathf(validator.path, "cannot use value %d as %s", n, v.Type.NamedType)
}
rv = reflect.ValueOf(n)
} else if v.Type.NamedType == "Float" {
f, err := jsonNumber.Float64()
if err != nil {
return nil, gqlerror.ErrorPathf(validator.path, "cannot use value %f as %s", f, v.Type.NamedType)
}
rv = reflect.ValueOf(f)

}
}
if rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
rv = rv.Elem()
}
Expand Down
14 changes: 11 additions & 3 deletions validator/vars_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package validator_test

import (
"encoding/json"
"io/ioutil"
"testing"

Expand Down Expand Up @@ -285,10 +284,19 @@ func TestValidateVars(t *testing.T) {
t.Run("Json Number -> Int", func(t *testing.T) {
q := gqlparser.MustLoadQuery(schema, `query foo($var: Int) { optionalIntArg(i: $var) }`)
vars, gerr := validator.VariableValues(schema, q.Operations.ForName(""), map[string]interface{}{
"var": json.Number("10"),
"var": 10,
})
require.Nil(t, gerr)
require.Equal(t, json.Number("10"), vars["var"])
require.Equal(t, 10, vars["var"])
})

t.Run("Json Number -> Float", func(t *testing.T) {
q := gqlparser.MustLoadQuery(schema, `query foo($var: Float!) { floatArg(i: $var) }`)
vars, gerr := validator.VariableValues(schema, q.Operations.ForName(""), map[string]interface{}{
"var": 10.2,
})
require.Nil(t, gerr)
require.Equal(t, 10.2, vars["var"])
})

t.Run("Nil -> Int", func(t *testing.T) {
Expand Down