forked from hasura/go-graphql-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql.go
411 lines (351 loc) · 12.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package graphql
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/hasura/go-graphql-client/pkg/jsonutil"
)
// This function allows you to tweak the HTTP request. It might be useful to set authentication
// headers amongst other things
type RequestModifier func(*http.Request)
// Client is a GraphQL client.
type Client struct {
url string // GraphQL server URL.
httpClient *http.Client
requestModifier RequestModifier
debug bool
}
// NewClient creates a GraphQL client targeting the specified GraphQL server URL.
// If httpClient is nil, then http.DefaultClient is used.
func NewClient(url string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
url: url,
httpClient: httpClient,
requestModifier: nil,
}
}
// Query executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}, options ...Option) error {
return c.do(ctx, queryOperation, q, variables, options...)
}
// NamedQuery executes a single GraphQL query request, with operation name
//
// Deprecated: this is the shortcut of Query method, with NewOperationName option
func (c *Client) NamedQuery(ctx context.Context, name string, q interface{}, variables map[string]interface{}, options ...Option) error {
return c.do(ctx, queryOperation, q, variables, append(options, OperationName(name))...)
}
// Mutate executes a single GraphQL mutation request,
// with a mutation derived from m, populating the response into it.
// m should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}, options ...Option) error {
return c.do(ctx, mutationOperation, m, variables, options...)
}
// NamedMutate executes a single GraphQL mutation request, with operation name
//
// Deprecated: this is the shortcut of Mutate method, with NewOperationName option
func (c *Client) NamedMutate(ctx context.Context, name string, m interface{}, variables map[string]interface{}, options ...Option) error {
return c.do(ctx, mutationOperation, m, variables, append(options, OperationName(name))...)
}
// Query executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
// return raw bytes message.
func (c *Client) QueryRaw(ctx context.Context, q interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) {
return c.doRaw(ctx, queryOperation, q, variables, options...)
}
// NamedQueryRaw executes a single GraphQL query request, with operation name
// return raw bytes message.
func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) {
return c.doRaw(ctx, queryOperation, q, variables, append(options, OperationName(name))...)
}
// MutateRaw executes a single GraphQL mutation request,
// with a mutation derived from m, populating the response into it.
// m should be a pointer to struct that corresponds to the GraphQL schema.
// return raw bytes message.
func (c *Client) MutateRaw(ctx context.Context, m interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) {
return c.doRaw(ctx, mutationOperation, m, variables, options...)
}
// NamedMutateRaw executes a single GraphQL mutation request, with operation name
// return raw bytes message.
func (c *Client) NamedMutateRaw(ctx context.Context, name string, m interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) {
return c.doRaw(ctx, mutationOperation, m, variables, append(options, OperationName(name))...)
}
// buildAndRequest the common method that builds and send graphql request
func (c *Client) buildAndRequest(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) ([]byte, *http.Response, io.Reader, Errors) {
var query string
var err error
switch op {
case queryOperation:
query, err = ConstructQuery(v, variables, options...)
case mutationOperation:
query, err = ConstructMutation(v, variables, options...)
}
if err != nil {
return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)}
}
return c.request(ctx, query, variables, options...)
}
// Request the common method that send graphql request
func (c *Client) request(ctx context.Context, query string, variables map[string]interface{}, options ...Option) ([]byte, *http.Response, io.Reader, Errors) {
in := struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}{
Query: query,
Variables: variables,
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(in)
if err != nil {
return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)}
}
reqReader := bytes.NewReader(buf.Bytes())
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, reqReader)
if err != nil {
e := newError(ErrRequestError, fmt.Errorf("problem constructing request: %w", err))
if c.debug {
e = e.withRequest(request, reqReader)
}
return nil, nil, nil, Errors{e}
}
request.Header.Add("Content-Type", "application/json")
if c.requestModifier != nil {
c.requestModifier(request)
}
resp, err := c.httpClient.Do(request)
if c.debug {
reqReader.Seek(0, io.SeekStart)
}
if err != nil {
e := newError(ErrRequestError, err)
if c.debug {
e = e.withRequest(request, reqReader)
}
return nil, nil, nil, Errors{e}
}
defer resp.Body.Close()
r := resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gr, err := gzip.NewReader(r)
if err != nil {
return nil, nil, nil, Errors{newError(ErrJsonDecode, fmt.Errorf("problem trying to create gzip reader: %w", err))}
}
defer gr.Close()
r = gr
}
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
err := newError(ErrRequestError, fmt.Errorf("%v; body: %q", resp.Status, body))
if c.debug {
err = err.withRequest(request, reqReader)
}
return nil, nil, nil, Errors{err}
}
var out struct {
Data *json.RawMessage
Errors Errors
}
// copy the response reader for debugging
var respReader *bytes.Reader
if c.debug {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, nil, Errors{newError(ErrJsonDecode, err)}
}
respReader = bytes.NewReader(body)
r = io.NopCloser(respReader)
}
err = json.NewDecoder(r).Decode(&out)
if c.debug {
respReader.Seek(0, io.SeekStart)
}
if err != nil {
we := newError(ErrJsonDecode, err)
if c.debug {
we = we.withRequest(request, reqReader).
withResponse(resp, respReader)
}
return nil, nil, nil, Errors{we}
}
var rawData []byte
if out.Data != nil && len(*out.Data) > 0 {
rawData = []byte(*out.Data)
}
if len(out.Errors) > 0 {
if c.debug && (out.Errors[0].Extensions == nil || out.Errors[0].Extensions["request"] == nil) {
out.Errors[0] = out.Errors[0].
withRequest(request, reqReader).
withResponse(resp, respReader)
}
return rawData, resp, respReader, out.Errors
}
return rawData, resp, respReader, nil
}
// do executes a single GraphQL operation.
// return raw message and error
func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) {
data, _, _, err := c.buildAndRequest(ctx, op, v, variables, options...)
if len(err) > 0 {
return data, err
}
return data, nil
}
// do executes a single GraphQL operation and unmarshal json.
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) error {
data, resp, respBuf, errs := c.buildAndRequest(ctx, op, v, variables, options...)
return c.processResponse(v, data, resp, respBuf, errs)
}
// Executes a pre-built query and unmarshals the response into v. Unlike the Query method you have to specify in the query the
// fields that you want to receive as they are not inferred from v. This method is useful if you need to build the query dynamically.
func (c *Client) Exec(ctx context.Context, query string, v interface{}, variables map[string]interface{}, options ...Option) error {
data, resp, respBuf, errs := c.request(ctx, query, variables, options...)
return c.processResponse(v, data, resp, respBuf, errs)
}
// Executes a pre-built query and returns the raw json message. Unlike the Query method you have to specify in the query the
// fields that you want to receive as they are not inferred from the interface. This method is useful if you need to build the query dynamically.
func (c *Client) ExecRaw(ctx context.Context, query string, variables map[string]interface{}, options ...Option) ([]byte, error) {
data, _, _, errs := c.request(ctx, query, variables, options...)
if len(errs) > 0 {
return data, errs
}
return data, nil
}
func (c *Client) processResponse(v interface{}, data []byte, resp *http.Response, respBuf io.Reader, errs Errors) error {
if len(data) > 0 {
err := jsonutil.UnmarshalGraphQL(data, v)
if err != nil {
we := newError(ErrGraphQLDecode, err)
if c.debug {
we = we.withResponse(resp, respBuf)
}
errs = append(errs, we)
}
}
if len(errs) > 0 {
return errs
}
return nil
}
// Returns a copy of the client with the request modifier set. This allows you to reuse the same
// TCP connection for multiple slightly different requests to the same server
// (i.e. different authentication headers for multitenant applications)
func (c *Client) WithRequestModifier(f RequestModifier) *Client {
return &Client{
url: c.url,
httpClient: c.httpClient,
requestModifier: f,
}
}
// WithDebug enable debug mode to print internal error detail
func (c *Client) WithDebug(debug bool) *Client {
return &Client{
url: c.url,
httpClient: c.httpClient,
requestModifier: c.requestModifier,
debug: debug,
}
}
// errors represents the "errors" array in a response from a GraphQL server.
// If returned via error interface, the slice is expected to contain at least 1 element.
//
// Specification: https://facebook.github.io/graphql/#sec-Errors.
type Errors []Error
type Error struct {
Message string `json:"message"`
Extensions map[string]interface{} `json:"extensions"`
Locations []struct {
Line int `json:"line"`
Column int `json:"column"`
} `json:"locations"`
}
// Error implements error interface.
func (e Error) Error() string {
return fmt.Sprintf("Message: %s, Locations: %+v", e.Message, e.Locations)
}
// Error implements error interface.
func (e Errors) Error() string {
b := strings.Builder{}
for _, err := range e {
b.WriteString(err.Error())
}
return b.String()
}
func (e Error) getInternalExtension() map[string]interface{} {
if e.Extensions == nil {
return make(map[string]interface{})
}
if ex, ok := e.Extensions["internal"]; ok {
return ex.(map[string]interface{})
}
return make(map[string]interface{})
}
func newError(code string, err error) Error {
return Error{
Message: err.Error(),
Extensions: map[string]interface{}{
"code": code,
},
}
}
func (e Error) withRequest(req *http.Request, bodyReader io.Reader) Error {
internal := e.getInternalExtension()
bodyBytes, err := ioutil.ReadAll(bodyReader)
if err != nil {
internal["error"] = err
} else {
internal["request"] = map[string]interface{}{
"headers": req.Header,
"body": string(bodyBytes),
}
}
if e.Extensions == nil {
e.Extensions = make(map[string]interface{})
}
e.Extensions["internal"] = internal
return e
}
func (e Error) withResponse(res *http.Response, bodyReader io.Reader) Error {
internal := e.getInternalExtension()
bodyBytes, err := ioutil.ReadAll(bodyReader)
if err != nil {
internal["error"] = err
} else {
internal["response"] = map[string]interface{}{
"headers": res.Header,
"body": string(bodyBytes),
}
}
e.Extensions["internal"] = internal
return e
}
// UnmarshalGraphQL parses the JSON-encoded GraphQL response data and stores
// the result in the GraphQL query data structure pointed to by v.
//
// The implementation is created on top of the JSON tokenizer available
// in "encoding/json".Decoder.
// This function is re-exported from the internal package
func UnmarshalGraphQL(data []byte, v interface{}) error {
return jsonutil.UnmarshalGraphQL(data, v)
}
type operationType uint8
const (
queryOperation operationType = iota
mutationOperation
// subscriptionOperation // Unused.
ErrRequestError = "request_error"
ErrJsonEncode = "json_encode_error"
ErrJsonDecode = "json_decode_error"
ErrGraphQLEncode = "graphql_encode_error"
ErrGraphQLDecode = "graphql_decode_error"
)