Skip to content

Commit

Permalink
Merge pull request #394 from graphql-go/examples-concurrent-fields
Browse files Browse the repository at this point in the history
examples: adds simple example for concurrent-resolvers
  • Loading branch information
chris-ramon authored Sep 11, 2018
2 parents cd6ef8d + bbe1508 commit 65dbc73
Showing 1 changed file with 108 additions and 0 deletions.
108 changes: 108 additions & 0 deletions examples/concurrent-resolvers/main.go
Original file line number Diff line number Diff line change
@@ -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"
}
}
}
*/
}

0 comments on commit 65dbc73

Please sign in to comment.