Skip to content

Commit

Permalink
treat arrays as iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Flint committed May 25, 2018
1 parent 51e8a07 commit b2eedbf
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ func completeListValue(eCtx *executionContext, returnType *List, fieldASTs []*as
parentTypeName = info.ParentType.Name()
}
err := invariantf(
resultVal.IsValid() && resultVal.Type().Kind() == reflect.Slice,
resultVal.IsValid() && isIterable(result),
"User Error: expected iterable, but did not find one "+
"for field %v.%v.", parentTypeName, info.FieldName)

Expand Down
19 changes: 18 additions & 1 deletion lists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -773,10 +773,27 @@ func TestLists_UserErrorExpectIterableButDidNotGetOne(t *testing.T) {
},
Errors: []gqlerrors.FormattedError{
{
Message: "User Error: expected iterable, but did not find one for field DataType.test.",
Message: "User Error: aexpected iterable, but did not find one for field DataType.test.",
Locations: []location.SourceLocation{},
},
},
}
checkList(t, ttype, data, expected)
}

func TestLists_ArrayOfNullableObjects_ContainsValues(t *testing.T) {
ttype := graphql.NewList(graphql.Int)
data := [2]interface{}{
1, 2,
}
expected := &graphql.Result{
Data: map[string]interface{}{
"nest": map[string]interface{}{
"test": []interface{}{
1, 2,
},
},
},
}
checkList(t, ttype, data, expected)
}
9 changes: 9 additions & 0 deletions values.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,15 @@ func isNullish(src interface{}) bool {
return false
}

// Returns true if src is a slice or an array
func isIterable(src interface{}) bool {
if src == nil {
return false
}
t := reflect.TypeOf(src)
return t.Kind() == reflect.Slice || t.Kind() == reflect.Array
}

/**
* Produces a value given a GraphQL Value AST.
*
Expand Down
18 changes: 18 additions & 0 deletions values_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package graphql

import "testing"

func TestIsIterable(t *testing.T) {
if !isIterable([]int{}) {
t.Fatal("expected isIterable to return true for a slice, got false")
}
if !isIterable([]int{}) {
t.Fatal("expected isIterable to return true for an array, got false")
}
if isIterable(1) {
t.Fatal("expected isIterable to return false for an int, got true")
}
if isIterable(nil) {
t.Fatal("expected isIterable to return false for nil, got true")
}
}

0 comments on commit b2eedbf

Please sign in to comment.