-
Notifications
You must be signed in to change notification settings - Fork 1
/
graphql.go
83 lines (69 loc) · 1.8 KB
/
graphql.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
package authorizer
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
// GraphQLRequest is object used to make graphql queries
type GraphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
type GraphQLError struct {
Message string `json:"message"`
Path []string `json:"path"`
}
type GraphQLResponse struct {
Errors []*GraphQLError `json:"errors"`
Data interface{} `json:"data"`
}
func (c *AuthorizerClient) ExecuteGraphQL(req *GraphQLRequest, headers map[string]string) ([]byte, error) {
// Marshal it into JSON prior to requesting
jsonReq, err := json.Marshal(req)
if err != nil {
return nil, err
}
client := http.Client{}
httpReq, err := http.NewRequest(http.MethodPost, c.AuthorizerURL+"/graphql", bytes.NewReader(jsonReq))
if err != nil {
return nil, err
}
// set the content type for http request
httpReq.Header.Set("Content-Type", "application/json")
// set the default extra headers
for key, val := range c.ExtraHeaders {
httpReq.Header.Add(key, val)
}
// set the headers for this request
if headers != nil {
for key, val := range headers {
httpReq.Header.Add(key, val)
}
}
res, err := client.Do(httpReq)
if err != nil {
return nil, err
}
// Need to close the response stream, once response is read.
// Hence defer close. It will automatically take care of it.
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var gqlRes *GraphQLResponse
err = json.Unmarshal(bodyBytes, &gqlRes)
if err != nil {
return nil, err
}
if len(gqlRes.Errors) > 0 {
return nil, errors.New(gqlRes.Errors[0].Message)
}
dataBytes, err := json.Marshal(gqlRes.Data)
if err != nil {
return nil, err
}
return dataBytes, nil
}