Skip to content

Commit

Permalink
Merge pull request #33 from danielgtaylor/fix-zero-slice
Browse files Browse the repository at this point in the history
fix: better handling of zero values; no panic for generic types
  • Loading branch information
danielgtaylor committed Mar 22, 2022
2 parents 78d423d + d0e1f45 commit e04f23d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
4 changes: 2 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,13 @@ func shallowStructToMap(v reflect.Value, result map[string]interface{}) {
if name == "-" {
continue
}
if len(parts) == 2 && parts[1] == "omitempty" && v.Field(i).IsZero() {
if len(parts) > 1 && parts[1] == "omitempty" {
vf := v.Field(i)
zero := vf.IsZero()
if vf.Kind() == reflect.Slice || vf.Kind() == reflect.Map {
// Special case: omit if they have no items in them to match the
// JSON encoder.
zero = vf.Len() > 0
zero = vf.Len() == 0
}
if zero {
continue
Expand Down
4 changes: 3 additions & 1 deletion graphql_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func getFields(typ reflect.Type) []reflect.StructField {
if newTyp.Kind() == reflect.Ptr {
newTyp = newTyp.Elem()
}
fields = append(fields, getFields(newTyp)...)
if newTyp.Kind() == reflect.Struct {
fields = append(fields, getFields(newTyp)...)
}
}

return fields
Expand Down
6 changes: 5 additions & 1 deletion schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,9 @@ func getFields(typ reflect.Type) []reflect.StructField {
if newTyp.Kind() == reflect.Ptr {
newTyp = newTyp.Elem()
}
fields = append(fields, getFields(newTyp)...)
if newTyp.Kind() == reflect.Struct {
fields = append(fields, getFields(newTyp)...)
}
}

return fields
Expand Down Expand Up @@ -542,6 +544,8 @@ func GenerateWithMode(t reflect.Type, mode Mode, schema *Schema) (*Schema, error
return GenerateWithMode(t.Elem(), mode, schema)
case reflect.Interface:
// Interfaces can be any type.
case reflect.Uintptr, reflect.UnsafePointer, reflect.Func:
// Ignored...
default:
return nil, fmt.Errorf("unsupported type %s from %s", t.Kind(), t)
}
Expand Down

0 comments on commit e04f23d

Please sign in to comment.