1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
| package main
import (
"encoding/json"
"fmt"
"log"
"time"
"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) {
type result struct {
data interface{}
err error
}
ch := make(chan *result, 1)
go func() {
defer close(ch)
time.Sleep(1 * time.Second)
foo := &Foo{Name: "Foo's name"}
ch <- &result{data: foo, err: nil}
}()
r := <-ch
return r.data, r.err
},
},
"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)
time.Sleep(1 * time.Second)
bar := &Bar{Name: "Bar's name"}
ch <- &result{data: bar, err: nil}
}()
r := <-ch
return r.data, r.err
},
},
},
})
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"
}
}
}
*/
}
|