Skip to content

Commit e1bf8d6

Browse files
committed
Fix panic in DefaultResolveFn if uses the string type alias in source key
This closes graphql-go#700.
1 parent a546af7 commit e1bf8d6

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

executor.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -995,7 +995,20 @@ func DefaultResolveFn(p ResolveParams) (interface{}, error) {
995995

996996
// Try accessing as map via reflection
997997
if r := reflect.ValueOf(p.Source); r.Kind() == reflect.Map && r.Type().Key().Kind() == reflect.String {
998-
val := r.MapIndex(reflect.ValueOf(p.Info.FieldName))
998+
fieldNameValue := reflect.ValueOf(p.Info.FieldName)
999+
mapKeyType := r.Type().Key()
1000+
// The map key type might be a string type alias and its underlying type is string,
1001+
// but it will be panic if we try to use it as a string value in `MapIndex`.
1002+
// So we need to convert the value of the field name to the map key type before
1003+
// using it as a map key.
1004+
//
1005+
// Related issue: https://github.com/graphql-go/graphql/issues/700
1006+
if !fieldNameValue.CanConvert(mapKeyType) {
1007+
return nil, nil
1008+
}
1009+
fieldNameValue = fieldNameValue.Convert(mapKeyType)
1010+
1011+
val := r.MapIndex(fieldNameValue)
9991012
if val.IsValid() {
10001013
property := val.Interface()
10011014
if val.Type().Kind() == reflect.Func {

executor_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ import (
1515
"github.com/graphql-go/graphql/testutil"
1616
)
1717

18+
func TestDefaultResolveFn(t *testing.T) {
19+
type Key string
20+
type Source map[Key]interface{}
21+
source := Source{
22+
"foo": "bar",
23+
}
24+
graphql.DefaultResolveFn(graphql.ResolveParams{
25+
Source: source,
26+
})
27+
}
28+
1829
func TestExecutesArbitraryCode(t *testing.T) {
1930

2031
deepData := map[string]interface{}{}

0 commit comments

Comments
 (0)