-
Notifications
You must be signed in to change notification settings - Fork 232
/
client.go
238 lines (199 loc) · 5.95 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
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
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/CircleCI-Public/circleci-cli/version"
"github.com/pkg/errors"
)
// A Client is an HTTP client for our GraphQL endpoint.
type Client struct {
Debug bool
Endpoint string
Host string
Token string
httpClient *http.Client
}
// NewClient returns a reference to a Client.
func NewClient(host, endpoint, token string, debug bool) *Client {
return &Client{
httpClient: http.DefaultClient,
Endpoint: endpoint,
Host: host,
Token: token,
Debug: debug,
}
}
// Reset replaces the existing fields with out creating a new client instance
func (cl *Client) Reset(host, endpoint, token string, debug bool) {
cl.Endpoint = endpoint
cl.Host = host
cl.Token = token
cl.Debug = debug
}
// NewRequest returns a new GraphQL request.
func NewRequest(query string) *Request {
request := &Request{
Query: query,
Variables: make(map[string]interface{}),
Header: make(map[string][]string),
}
request.Header.Set("User-Agent", version.UserAgent())
return request
}
// Request is a GraphQL request.
type Request struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
// Header represent any request headers that will be set
// when the request is made.
Header http.Header `json:"-"`
}
// SetToken sets the Authorization header for the request with the given token.
func (request *Request) SetToken(token string) {
request.Header.Set("Authorization", token)
}
// Var sets a variable.
func (request *Request) Var(key string, value interface{}) {
request.Variables[key] = value
}
// Encode will return a buffer of the JSON encoded request body
func (request *Request) Encode() (bytes.Buffer, error) {
var body bytes.Buffer
err := json.NewEncoder(&body).Encode(request)
return body, err
}
// Response wraps the result from our GraphQL server response including out-of-band errors and the data itself.
type Response struct {
Data interface{}
Errors ResponseErrorsCollection
}
// ResponseErrorsCollection represents a slice of errors returned by the GraphQL server out-of-band from the actual data.
type ResponseErrorsCollection []ResponseError
// ResponseError represents the key-value pair of data returned by the GraphQL server to represent errors.
type ResponseError struct {
Message string
}
// Error turns a ResponseErrorsCollection into an acceptable error string that can be printed to the user.
func (errs ResponseErrorsCollection) Error() string {
messages := []string{}
for i := range errs {
messages = append(messages, errs[i].Message)
}
return strings.Join(messages, "\n")
}
// getServerAddress returns the full address to the server
func getServerAddress(host, endpoint string) (string, error) {
// 1. Parse the endpoint
e, err := url.Parse(endpoint)
if err != nil {
return "", errors.Wrapf(err, "Parsing endpoint '%s'", endpoint)
}
// 2. Parse the host
h, err := url.Parse(host)
if err != nil {
return "", errors.Wrapf(err, "Parsing host '%s'", host)
}
if !h.IsAbs() {
return h.String(), fmt.Errorf("Host (%s) must be absolute URL, including scheme", host)
}
// 3. Resolve the two URLs using host as the base
// We use ResolveReference which has specific behavior we can rely for
// older configurations which included the absolute path for the endpoint flag.
//
// https://golang.org/pkg/net/url/#URL.ResolveReference
//
// Specifically this function always returns the reference (endpoint) if provided an absolute URL.
// This way we can safely introduce --host and merge the two.
return h.ResolveReference(e).String(), err
}
func prepareRequest(ctx context.Context, address string, request *Request) (*http.Request, error) {
requestBody, err := request.Encode()
if err != nil {
return nil, err
}
r, err := http.NewRequest(http.MethodPost, address, &requestBody)
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", "application/json; charset=utf-8")
r.Header.Set("Accept", "application/json; charset=utf-8")
for key, values := range request.Header {
for _, value := range values {
r.Header.Add(key, value)
}
}
r = r.WithContext(ctx)
return r, nil
}
// Run sends an HTTP request to the GraphQL server and deserializes the response or returns an error.
// TODO(zzak): This function is fairly complex, we should refactor it
// nolint: gocyclo
func (cl *Client) Run(request *Request, resp interface{}) error {
l := log.New(os.Stderr, "", 0)
ctx := context.Background()
select {
case <-ctx.Done():
return ctx.Err()
default:
}
address, err := getServerAddress(cl.Host, cl.Endpoint)
if err != nil {
return err
}
req, err := prepareRequest(ctx, address, request)
if err != nil {
return err
}
if cl.Debug {
l.Printf(">> variables: %v", request.Variables)
l.Printf(">> query: %s", request.Query)
}
res, err := cl.httpClient.Do(req)
if err != nil {
return err
}
defer func() {
responseBodyCloseErr := res.Body.Close()
if responseBodyCloseErr != nil {
l.Printf(responseBodyCloseErr.Error())
}
}()
if cl.Debug {
l.Printf("<< request id: %s", res.Header.Get("X-Request-Id"))
l.Printf("<< result status: %s", res.Status)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failure calling GraphQL API: %s", res.Status)
}
// Request.Body is an io.ReadCloser it can only be read once
if cl.Debug {
var bodyBytes []byte
if res.Body != nil {
bodyBytes, err = ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "reading response")
}
l.Printf("<< %s", string(bodyBytes))
// Restore the io.ReadCloser to its original state
res.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
}
}
wrappedResponse := &Response{
Data: resp,
}
if err := json.NewDecoder(res.Body).Decode(&wrappedResponse); err != nil {
return errors.Wrap(err, "decoding response")
}
if len(wrappedResponse.Errors) > 0 {
return wrappedResponse.Errors
}
return nil
}