Skip to content

Commit

Permalink
Fix panic in DefaultResolveFn if uses the string type alias in source…
Browse files Browse the repository at this point in the history
… key

This closes graphql-go#700.
  • Loading branch information
git-hulk committed Nov 25, 2024
1 parent a546af7 commit e1bf8d6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
15 changes: 14 additions & 1 deletion executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -995,7 +995,20 @@ func DefaultResolveFn(p ResolveParams) (interface{}, error) {

// Try accessing as map via reflection
if r := reflect.ValueOf(p.Source); r.Kind() == reflect.Map && r.Type().Key().Kind() == reflect.String {
val := r.MapIndex(reflect.ValueOf(p.Info.FieldName))
fieldNameValue := reflect.ValueOf(p.Info.FieldName)
mapKeyType := r.Type().Key()
// The map key type might be a string type alias and its underlying type is string,
// but it will be panic if we try to use it as a string value in `MapIndex`.
// So we need to convert the value of the field name to the map key type before
// using it as a map key.
//
// Related issue: https://github.com/graphql-go/graphql/issues/700
if !fieldNameValue.CanConvert(mapKeyType) {
return nil, nil
}
fieldNameValue = fieldNameValue.Convert(mapKeyType)

val := r.MapIndex(fieldNameValue)
if val.IsValid() {
property := val.Interface()
if val.Type().Kind() == reflect.Func {
Expand Down
11 changes: 11 additions & 0 deletions executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ import (
"github.com/graphql-go/graphql/testutil"
)

func TestDefaultResolveFn(t *testing.T) {
type Key string
type Source map[Key]interface{}
source := Source{
"foo": "bar",
}
graphql.DefaultResolveFn(graphql.ResolveParams{
Source: source,
})
}

func TestExecutesArbitraryCode(t *testing.T) {

deepData := map[string]interface{}{}
Expand Down

0 comments on commit e1bf8d6

Please sign in to comment.