forked from hasura/go-graphql-client
/
client.go
105 lines (90 loc) · 1.96 KB
/
client.go
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
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
graphql "github.com/llehouerou/go-graphql-client"
)
func getServerEndpoint() string {
return fmt.Sprintf("http://localhost:%d/graphql", httpPort)
}
func startSubscription() error {
client := graphql.NewSubscriptionClient(getServerEndpoint()).
WithConnectionParams(map[string]interface{}{
"headers": map[string]string{
"foo": "bar",
},
}).WithLog(log.Println).
WithoutLogTypes(graphql.GQL_DATA, graphql.GQL_CONNECTION_KEEP_ALIVE).
OnError(func(sc *graphql.SubscriptionClient, err error) error {
log.Print("err", err)
return err
})
defer client.Close()
/*
subscription {
helloSaid {
id
msg
}
}
*/
var sub struct {
HelloSaid struct {
ID graphql.ID
Message string `graphql:"msg"`
} `graphql:"helloSaid"`
}
subId, err := client.Subscribe(sub, nil, func(data []byte, err error) error {
if err != nil {
log.Println(err)
return nil
}
if data == nil {
return nil
}
log.Println(string(data))
return nil
})
if err != nil {
panic(err)
}
// automatically unsubscribe after 10 seconds
go func() {
time.Sleep(10 * time.Second)
client.Unsubscribe(subId)
}()
return client.Run()
}
// send hello mutations to the graphql server, so the subscription client can receive messages
func startSendHello() {
client := graphql.NewClient(getServerEndpoint(), &http.Client{Transport: http.DefaultTransport})
// stop until the subscription client is connected
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
/*
mutation ($msg: String!) {
sayHello(msg: $msg) {
id
msg
}
}
*/
var q struct {
SayHello struct {
ID graphql.ID
Msg string
} `graphql:"sayHello(msg: $msg)"`
}
variables := map[string]interface{}{
"msg": randomID(),
}
err := client.Mutate(context.Background(), &q, variables, graphql.OperationName("SayHello"))
if err != nil {
fmt.Println(err)
}
time.Sleep(time.Second)
}
}