-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgql_client.go
325 lines (284 loc) · 7.5 KB
/
gql_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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package client
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/websocket"
"github.com/machinebox/graphql"
)
const (
connectionInitMsg = "connection_init" // Client -> Server
startMsg = "start" // Client -> Server
sendMessageMutation = `
mutation sendMessage($body: String!, $originId: String!, $originThreadId: String!, $username: String!, $authorOriginId: String!, $authorAvatarUrl: String!, $attachments: [AttachmentInput!]!) {
sendMessage(
input: {
body: $body,
originId: $originId,
originThreadId: $originThreadId,
author: {
username: $username,
originId: $authorOriginId,
avatarUrl: $authorAvatarUrl
},
attachments: $attachments
}
) {
id
}
}`
messageReceivedSubscription = `
subscription {
messageReceived {
message {
body
id
originId
attachments {
type
sourceUrl
originId
id
}
thread {
id
originId
name
}
threadGroupId
author {
username
originId
avatarUrl
}
}
targetThreadId
}
}`
setSearchResultMutation = `
mutation setSearchResponse($q: String!, $res: [ThreadSearchResultInput!]!) {
setSearchResponse(forQuery:$q, threads:$res) {
threads {
originId
name
iconUrl
}
forQuery
}
}`
searchRequestSubscription = `
subscription {
subscribeToSearchRequests {
query
}
}`
requestConfigurationRequest = `
subscription confRequest($fields: [ConfigurationField!]!){
configurationReceived(configuration:{fields: $fields}) {
fieldValues {
name
value
}
}
}`
setInstanceStatusMutation = `
mutation {
setInstanceStatus(status:INITIALIZED) {
status
name
}
}`
)
// MessageAuthor holds information about single message's atuhor
type MessageAuthor struct {
ID string `json:"id"`
Username string `json:"username"`
OriginID string `json:"originId"`
AvatarURL string `json:"avatarUrl"`
}
type AttachmentInput struct {
OriginID string `json:"originId"`
Type string `json:"type"`
SourceURL string `json:"sourceUrl"`
}
type Attachment struct {
ID string `json:"id"`
OriginID string `json:"originId"`
Type string `json:"type"`
SourceURL string `json:"sourceUrl"`
}
// Thread holds information about single thread
type Thread struct {
ID string `json:"id"`
Name string `json:"name"`
OriginID string `json:"originId"`
ThreadGroupID string `json:"threadGroupId"`
IconURL string `json:"iconUrl"`
ServiceInstanceID string `json:"serviceInstanceId"`
}
// Message holds information about single message
type Message struct {
ID string `json:"string"`
OriginID string `json:"originId"`
Author MessageAuthor `json:"author"`
Thread Thread `json:"thread"`
Body string `json:"body"`
ThreadGroupID string `json:"threadGroupId"`
Attachments []Attachment `json:"attachments"`
}
type SearchThreadInput struct {
OriginID string `json:"originId"`
Name string `json:"name"`
IconURL string `json:"iconUrl"`
}
// ErrorLocation holds data about location of gql error
type ErrorLocation struct {
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
}
// ErrorMessage holds data about graphql error
type ErrorMessage struct {
Message string `json:"message,omitempty"`
Locations []*ErrorLocation `json:"locations,omitempty"`
}
// MessageReceived holds data about incoming message
type MessageReceived struct {
Message Message `json:"message"`
TargetThreadID string `json:"targetThreadId"`
}
type SearchRequest struct {
Query string `json:"query"`
}
type searchRequestPayload struct {
Data struct {
SubscribeToSearchRequests SearchRequest `json:"subscribeToSearchRequests"`
} `json:"data"`
}
type messageReceivedPayload struct {
Data struct {
MessageReceived MessageReceived `json:"messageReceived"`
} `json:"data"`
}
type configurationReceivedPayload struct {
Data struct {
ConfigurationReceived ConfigurationResponse `json:"configurationReceived"`
} `json:"data"`
}
type OperationMessage struct {
Payload PayloadMessage `json:"payload,omitempty"`
ID string `json:"id,omitempty"`
Type string `json:"type"`
}
// IncomingPayload is a struct holding graphql operation data
type IncomingPayload struct {
Payload *json.RawMessage `json:"payload,omitempty"`
Type string `json:"type"`
ID string `json:"id"`
}
type PayloadMessage struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
AccessToken string `json:"accessToken"`
}
type GQLClient struct {
WSUrl string
HTTPUrl string
Headers PayloadMessage
client *graphql.Client
wsConn *websocket.Conn
}
func NewGQLClient(wsUrl string, httpUrl string, headers PayloadMessage) *GQLClient {
return &GQLClient{
WSUrl: wsUrl,
HTTPUrl: httpUrl,
Headers: headers,
client: graphql.NewClient(httpUrl),
}
}
// Request sends a graphql requests to the core server and returns a pointer to map with result
func (gqc *GQLClient) Request(req *graphql.Request) (*map[string]interface{}, error) {
// make a request
req.Header.Add("Authentication", gqc.Headers.AccessToken)
ctx := context.Background()
var respData map[string]interface{}
if err := gqc.client.Run(ctx, req, &respData); err != nil {
return nil, err
}
return &respData, nil
}
func (gqc *GQLClient) ReadIncomingPayload() (*IncomingPayload, error) {
var msg IncomingPayload
err := gqc.wsConn.ReadJSON(&msg)
if err != nil {
panic(err)
}
return &msg, err
}
func (gqc *GQLClient) WriteOperationPacket(packet *OperationMessage) {
_ = gqc.wsConn.WriteJSON(packet)
}
func (gqc *GQLClient) Subscribe(query string, variables map[string]interface{}) string {
subID := GenerateID()
gqc.WriteOperationPacket(&OperationMessage{Type: startMsg, ID: subID, Payload: PayloadMessage{
Query: query,
Variables: variables,
}})
return subID
}
func (gqc *GQLClient) Connect() (<-chan *IncomingPayload, <-chan error) {
headers := make(http.Header)
headers.Add("Sec-Websocket-Protocol", "graphql-ws")
ws, _, err := websocket.DefaultDialer.Dial(gqc.WSUrl, headers)
if err != nil {
panic(err)
}
gqc.wsConn = ws
channel := make(chan *IncomingPayload)
errChan := make(chan error)
gqc.WriteOperationPacket(&OperationMessage{Type: connectionInitMsg, Payload: gqc.Headers})
_, _ = gqc.ReadIncomingPayload()
go func() {
defer close(channel)
defer close(errChan)
for {
msg, err := gqc.ReadIncomingPayload()
if err != nil {
errChan <- err
}
fmt.Println("got smth")
if msg.Type == "error" {
var errs []*ErrorMessage
err = json.Unmarshal(*msg.Payload, &errs)
fmt.Println(errs[0].Message)
}
fmt.Println(msg.ID)
channel <- msg
}
}()
return channel, errChan
}
type ConfigurationField struct {
Type string `json:"type"`
Name string `json:"name"`
DefaultValue string `json:"defaultValue"`
Optional bool `json:"optional"`
Hint string `json:"hint"`
Mask bool `json:"mask"`
}
type ConfigurationRequest struct {
Fields []ConfigurationField `json:"fields"`
}
type ConfigurationFieldResult struct {
Name string `json:"name"`
Value string `json:"value"`
}
type ConfigurationResponse struct {
FieldValues []ConfigurationFieldResult `json:"fieldValues"`
}
func GenerateID() string {
b := make([]byte, 4)
_, _ = rand.Read(b)
return fmt.Sprintf("%x", b)
}