Created
April 25, 2019 23:55
-
-
Save kellrott/823ca42c6310148e077af3b324f14bf6 to your computer and use it in GitHub Desktop.
Test code to take incoming GraphQL-Go query and inspect the AST for sub fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"github.com/graphql-go/graphql" | |
"github.com/graphql-go/graphql/language/ast" | |
) | |
func scanField(f *ast.Field, prefix string) { | |
fmt.Printf("%s%s -- %#v\n", prefix, f.Name.Value, f) | |
if f.SelectionSet != nil { | |
for _, s := range f.SelectionSet.Selections { | |
if k, ok := s.(*ast.Field); ok { | |
scanField(k, prefix + " ") | |
} | |
} | |
} | |
} | |
func main() { | |
// Schema | |
personObject := graphql.NewObject(graphql.ObjectConfig{Name: "Person", | |
Fields: graphql.Fields{"name": &graphql.Field{ | |
Type: graphql.String, | |
}}, | |
}) | |
personObject.AddFieldConfig("friend", &graphql.Field{ | |
Name: "Friend", | |
Type: personObject}) | |
fields := graphql.Fields{ | |
"hello": &graphql.Field{ | |
Type: graphql.String, | |
Resolve: func(p graphql.ResolveParams) (interface{}, error) { | |
return "world", nil | |
}, | |
}, | |
"person" : &graphql.Field{ | |
Type: personObject, | |
Resolve: func(p graphql.ResolveParams) (interface{}, error) { | |
fmt.Printf("main field: %#v\n", p.Info.FieldASTs) | |
for _, i := range p.Info.FieldASTs { | |
scanField(i, "") | |
} | |
return map[string]interface{}{"name" : "bob", "friend" : map[string]interface{}{ "name" : "Joe", | |
"friend" : map[string]interface{}{ "name" : "Sam" }, | |
} }, nil | |
}, | |
}, | |
} | |
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields} | |
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)} | |
schema, err := graphql.NewSchema(schemaConfig) | |
if err != nil { | |
log.Fatalf("failed to create new schema, error: %v", err) | |
} | |
// Query | |
query := ` | |
{ | |
person { | |
name | |
friend { name | |
friend { | |
name | |
} | |
} | |
} | |
} | |
` | |
params := graphql.Params{Schema: schema, RequestString: query} | |
r := graphql.Do(params) | |
if len(r.Errors) > 0 { | |
log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors) | |
} | |
rJSON, _ := json.Marshal(r) | |
fmt.Printf("%s \n", rJSON) // {“data”:{“hello”:”world”}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment