Skip to content

Commit a511a07

Browse files
committed
examples: adds simple example for concurrent-resolvers
1 parent 035d2b1 commit a511a07

File tree

1 file changed

+108
-0
lines changed
  • examples/concurrent-resolvers

1 file changed

+108
-0
lines changed

examples/concurrent-resolvers/main.go

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"log"
7+
8+
"github.com/graphql-go/graphql"
9+
)
10+
11+
type Foo struct {
12+
Name string
13+
}
14+
15+
var FieldFooType = graphql.NewObject(graphql.ObjectConfig{
16+
Name: "Foo",
17+
Fields: graphql.Fields{
18+
"name": &graphql.Field{Type: graphql.String},
19+
},
20+
})
21+
22+
type Bar struct {
23+
Name string
24+
}
25+
26+
var FieldBarType = graphql.NewObject(graphql.ObjectConfig{
27+
Name: "Bar",
28+
Fields: graphql.Fields{
29+
"name": &graphql.Field{Type: graphql.String},
30+
},
31+
})
32+
33+
// QueryType fields: `concurrentFieldFoo` and `concurrentFieldBar` are resolved
34+
// concurrently because they belong to the same field-level and their `Resolve`
35+
// function returns a function (thunk).
36+
var QueryType = graphql.NewObject(graphql.ObjectConfig{
37+
Name: "Query",
38+
Fields: graphql.Fields{
39+
"concurrentFieldFoo": &graphql.Field{
40+
Type: FieldFooType,
41+
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
42+
var foo = Foo{Name: "Foo's name"}
43+
return func() (interface{}, error) {
44+
return &foo, nil
45+
}, nil
46+
},
47+
},
48+
"concurrentFieldBar": &graphql.Field{
49+
Type: FieldBarType,
50+
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
51+
type result struct {
52+
data interface{}
53+
err error
54+
}
55+
ch := make(chan *result, 1)
56+
go func() {
57+
defer close(ch)
58+
bar := &Bar{Name: "Bar's name"}
59+
ch <- &result{data: bar, err: nil}
60+
}()
61+
return func() (interface{}, error) {
62+
r := <-ch
63+
return r.data, r.err
64+
}, nil
65+
},
66+
},
67+
},
68+
})
69+
70+
func main() {
71+
schema, err := graphql.NewSchema(graphql.SchemaConfig{
72+
Query: QueryType,
73+
})
74+
if err != nil {
75+
log.Fatal(err)
76+
}
77+
query := `
78+
query {
79+
concurrentFieldFoo {
80+
name
81+
}
82+
concurrentFieldBar {
83+
name
84+
}
85+
}
86+
`
87+
result := graphql.Do(graphql.Params{
88+
RequestString: query,
89+
Schema: schema,
90+
})
91+
b, err := json.Marshal(result)
92+
if err != nil {
93+
log.Fatal(err)
94+
}
95+
fmt.Printf("%s", b)
96+
/*
97+
{
98+
"data": {
99+
"concurrentFieldBar": {
100+
"name": "Bar's name"
101+
},
102+
"concurrentFieldFoo": {
103+
"name": "Foo's name"
104+
}
105+
}
106+
}
107+
*/
108+
}

0 commit comments

Comments
 (0)