Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples: adds simple example for concurrent-resolvers #394

Merged
merged 3 commits into from Sep 11, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
108 changes: 108 additions & 0 deletions examples/concurrent-resolvers/main.go
@@ -0,0 +1,108 @@
package main

import (
"encoding/json"
"fmt"
"log"

"github.com/graphql-go/graphql"
)

type Foo struct {
Name string
}

var FieldFooType = graphql.NewObject(graphql.ObjectConfig{
Name: "Foo",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
},
})

type Bar struct {
Name string
}

var FieldBarType = graphql.NewObject(graphql.ObjectConfig{
Name: "Bar",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
},
})

// QueryType fields: `concurrentFieldFoo` and `concurrentFieldBar` are resolved
// concurrently because they belong to the same field-level and their `Resolve`
// function returns a function (thunk).
var QueryType = graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"concurrentFieldFoo": &graphql.Field{
Type: FieldFooType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var foo = Foo{Name: "Foo's name"}
return func() (interface{}, error) {
return &foo, nil
}, nil
},
},
"concurrentFieldBar": &graphql.Field{
Type: FieldBarType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
type result struct {
data interface{}
err error
}
ch := make(chan *result, 1)
go func() {
defer close(ch)
bar := &Bar{Name: "Bar's name"}
ch <- &result{data: bar, err: nil}
}()
return func() (interface{}, error) {
r := <-ch
return r.data, r.err
}, nil
},
},
},
})

func main() {
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: QueryType,
})
if err != nil {
log.Fatal(err)
}
query := `
query {
concurrentFieldFoo {
name
}
concurrentFieldBar {
name
}
}
`
result := graphql.Do(graphql.Params{
RequestString: query,
Schema: schema,
})
b, err := json.Marshal(result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", b)
/*
{
"data": {
"concurrentFieldBar": {
"name": "Bar's name"
},
"concurrentFieldFoo": {
"name": "Foo's name"
}
}
}
*/
}