Skip to content

Commit

Permalink
Optimize hasGraphQLName and isGraphQLFragment
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed Jul 13, 2023
1 parent 85bf0c3 commit 7cef655
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions internal/jsonutil/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (d *decoder) decode() error {
continue
}
for i := 0; i < v.NumField(); i++ {
if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous {
if isGraphQLFragment(v.Type().Field(i).Tag) || v.Type().Field(i).Anonymous {
// Add GraphQL fragment or embedded struct.
d.vs = append(d.vs, []reflect.Value{v.Field(i)})
frontier = append(frontier, v.Field(i))
Expand Down Expand Up @@ -256,24 +256,23 @@ func (d *decoder) popAllVs() {
// that matches GraphQL name, or invalid reflect.Value if none found.
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value {
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).PkgPath != "" {
f := v.Type().Field(i)
if f.PkgPath != "" {
// Skip unexported field.
continue
}
if hasGraphQLName(v.Type().Field(i), name) {
if hasGraphQLName(f.Name, f.Tag, name) {
return v.Field(i)
}
}
return reflect.Value{}
}

// hasGraphQLName reports whether struct field f has GraphQL name.
func hasGraphQLName(f reflect.StructField, name string) bool {
value, ok := f.Tag.Lookup("graphql")
func hasGraphQLName(fname string, ftag reflect.StructTag, name string) bool {
value, ok := ftag.Lookup("graphql")
if !ok {
// TODO: caseconv package is relatively slow. Optimize it, then consider using it here.
//return caseconv.MixedCapsToLowerCamelCase(f.Name) == name
return strings.EqualFold(f.Name, name)
return strings.EqualFold(fname, name)
}
value = strings.TrimSpace(value) // TODO: Parse better.
if strings.HasPrefix(value, "...") {
Expand All @@ -289,8 +288,8 @@ func hasGraphQLName(f reflect.StructField, name string) bool {
}

// isGraphQLFragment reports whether struct field f is a GraphQL fragment.
func isGraphQLFragment(f reflect.StructField) bool {
value, ok := f.Tag.Lookup("graphql")
func isGraphQLFragment(ftag reflect.StructTag) bool {
value, ok := ftag.Lookup("graphql")
if !ok {
return false
}
Expand Down

0 comments on commit 7cef655

Please sign in to comment.