Skip to content

Instantly share code, notes, and snippets.

@andreas
Created June 9, 2016 10:55
Show Gist options
  • Save andreas/56bdbaca5c9d066553328501974a573b to your computer and use it in GitHub Desktop.
Save andreas/56bdbaca5c9d066553328501974a573b to your computer and use it in GitHub Desktop.
This gist shows the impact of resolving fields in parallel in graphql-go.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/graphql-go/graphql"
)
func main() {
// Schema
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
http.Get("http://fake-response.appspot.com/?sleep=2")
return "world", 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 := `
{
a: hello
b: hello
c: hello
d: hello
e: hello
}
`
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”}}
}
> go build && time ./hello-world
{"data":{"a":"world","b":"world","c":"world","d":"world","e":"world"}}
./hello-world 0.01s user 0.01s system 0% cpu 2.617 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment