-
Notifications
You must be signed in to change notification settings - Fork 67
/
client.go
724 lines (603 loc) · 18.4 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
package clientv2
import (
"bytes"
"compress/gzip"
"context"
"encoding"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/99designs/gqlgen/graphql"
"github.com/Yamashou/gqlgenc/graphqljson"
"github.com/vektah/gqlparser/v2/gqlerror"
)
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
Post(url, contentType string, body io.Reader) (*http.Response, error)
}
type GQLRequestInfo struct {
Request *Request
}
func NewGQLRequestInfo(r *Request) *GQLRequestInfo {
return &GQLRequestInfo{
Request: r,
}
}
type RequestInterceptorFunc func(ctx context.Context, req *http.Request, gqlInfo *GQLRequestInfo, res any) error
type RequestInterceptor func(ctx context.Context, req *http.Request, gqlInfo *GQLRequestInfo, res any, next RequestInterceptorFunc) error
func ChainInterceptor(interceptors ...RequestInterceptor) RequestInterceptor {
n := len(interceptors)
return func(ctx context.Context, req *http.Request, gqlInfo *GQLRequestInfo, res any, next RequestInterceptorFunc) error {
chainer := func(currentInter RequestInterceptor, currentFunc RequestInterceptorFunc) RequestInterceptorFunc {
return func(currentCtx context.Context, currentReq *http.Request, currentGqlInfo *GQLRequestInfo, currentRes any) error {
return currentInter(currentCtx, currentReq, currentGqlInfo, currentRes, currentFunc)
}
}
chainedHandler := next
for i := n - 1; i >= 0; i-- {
chainedHandler = chainer(interceptors[i], chainedHandler)
}
return chainedHandler(ctx, req, gqlInfo, res)
}
}
func UnsafeChainInterceptor(interceptors ...RequestInterceptor) RequestInterceptor {
n := len(interceptors)
return func(ctx context.Context, req *http.Request, gqlInfo *GQLRequestInfo, res any, next RequestInterceptorFunc) error {
chainer := func(currentInter RequestInterceptor, currentFunc RequestInterceptorFunc) RequestInterceptorFunc {
return func(currentCtx context.Context, currentReq *http.Request, currentGqlInfo *GQLRequestInfo, currentRes any) error {
return currentInter(currentCtx, currentReq, currentGqlInfo, currentRes, func(nextCtx context.Context, nextReq *http.Request, nextGqlInfo *GQLRequestInfo, nextRes any) error {
return currentFunc(nextCtx, nextReq, nextGqlInfo, nextRes)
})
}
}
chainedHandler := next
for i := n - 1; i >= 0; i-- {
chainedHandler = chainer(interceptors[i], chainedHandler)
}
return chainedHandler(ctx, req, gqlInfo, res)
}
}
// Client is the http client wrapper
type Client struct {
Client HttpClient
BaseURL string
RequestInterceptor RequestInterceptor
CustomDo RequestInterceptorFunc
ParseDataWhenErrors bool
IsUnsafeRequestInterceptor bool
}
// Request represents an outgoing GraphQL request
type Request struct {
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}
// NewClient creates a new http client wrapper
func NewClient(client HttpClient, baseURL string, options *Options, interceptors ...RequestInterceptor) *Client {
c := &Client{
Client: client,
BaseURL: baseURL,
RequestInterceptor: ChainInterceptor(append([]RequestInterceptor{func(ctx context.Context, requestSet *http.Request, gqlInfo *GQLRequestInfo, res any, next RequestInterceptorFunc) error {
return next(ctx, requestSet, gqlInfo, res)
}}, interceptors...)...),
}
if options != nil {
c.ParseDataWhenErrors = options.ParseDataAlongWithErrors
}
return c
}
func NewClientWithUnsafeRequestInterceptor(client HttpClient, baseURL string, options *Options, interceptors ...RequestInterceptor) *Client {
c := &Client{
Client: client,
BaseURL: baseURL,
RequestInterceptor: UnsafeChainInterceptor(append([]RequestInterceptor{func(ctx context.Context, requestSet *http.Request, gqlInfo *GQLRequestInfo, res any, next RequestInterceptorFunc) error {
return next(ctx, requestSet, gqlInfo, res)
}}, interceptors...)...),
IsUnsafeRequestInterceptor: true,
}
if options != nil {
c.ParseDataWhenErrors = options.ParseDataAlongWithErrors
}
return c
}
// Options is a struct that holds some client-specific options that can be passed to NewClient.
type Options struct {
// ParseDataAlongWithErrors is a flag that indicates whether the client should try to parse and return the data along with error
// when error appeared. So in the end you'll get list of gql errors and data.
ParseDataAlongWithErrors bool
}
// GqlErrorList is the struct of a standard graphql error response
type GqlErrorList struct {
Errors gqlerror.List `json:"errors"`
}
func (e *GqlErrorList) Error() string {
return e.Errors.Error()
}
// HTTPError is the error when a GqlErrorList cannot be parsed
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
}
// ErrorResponse represent an handled error
type ErrorResponse struct {
// populated when http status code is not OK
NetworkError *HTTPError `json:"networkErrors"`
// populated when http status code is OK but the server returned at least one graphql error
GqlErrors *gqlerror.List `json:"graphqlErrors"`
}
// HasErrors returns true when at least one error is declared
func (er *ErrorResponse) HasErrors() bool {
return er.NetworkError != nil || er.GqlErrors != nil
}
func (er *ErrorResponse) Error() string {
content, err := json.Marshal(er)
if err != nil {
return err.Error()
}
return string(content)
}
type MultipartFile struct {
File graphql.Upload
Index int
}
type MultipartFilesGroup struct {
Files []MultipartFile
IsMultiple bool
}
type FormField struct {
Name string
Value any
}
type header struct {
key, value string
}
// Post support send multipart form with files https://gqlgen.com/reference/file-upload/ https://github.com/jaydenseric/graphql-multipart-request-spec
func (c *Client) Post(ctx context.Context, operationName, query string, respData any, vars map[string]any, interceptors ...RequestInterceptor) error {
multipartFilesGroups, mapping, vars := parseMultipartFiles(vars)
r := &Request{
Query: query,
Variables: vars,
OperationName: operationName,
}
gqlInfo := NewGQLRequestInfo(r)
body := new(bytes.Buffer)
var headers []header
if len(multipartFilesGroups) > 0 {
contentType, err := prepareMultipartFormBody(
body,
[]FormField{
{
Name: "operations",
Value: r,
},
{
Name: "map",
Value: mapping,
},
},
multipartFilesGroups,
)
if err != nil {
return fmt.Errorf("failed to prepare form body: %w", err)
}
headers = append(headers, header{key: "Content-Type", value: contentType})
} else {
requestBody, err := MarshalJSON(r)
if err != nil {
return fmt.Errorf("encode: %w", err)
}
body = bytes.NewBuffer(requestBody)
headers = append(headers, header{key: "Content-Type", value: "application/json; charset=utf-8"})
headers = append(headers, header{key: "Accept", value: "application/json; charset=utf-8"})
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL, body)
if err != nil {
return fmt.Errorf("create request struct failed: %w", err)
}
for _, h := range headers {
req.Header.Set(h.key, h.value)
}
f := ChainInterceptor(append([]RequestInterceptor{c.RequestInterceptor}, interceptors...)...)
if c.IsUnsafeRequestInterceptor {
f = UnsafeChainInterceptor(append([]RequestInterceptor{c.RequestInterceptor}, interceptors...)...)
}
// if custom do is set, use it instead of the default one
if c.CustomDo != nil {
return f(ctx, req, gqlInfo, respData, c.CustomDo)
}
return f(ctx, req, gqlInfo, respData, c.do)
}
func parseMultipartFiles(
vars map[string]any,
) ([]MultipartFilesGroup, map[string][]string, map[string]any) {
var (
multipartFilesGroups []MultipartFilesGroup
mapping = map[string][]string{}
i = 0
)
for k, v := range vars {
switch item := v.(type) {
case graphql.Upload:
iStr := strconv.Itoa(i)
vars[k] = nil
mapping[iStr] = []string{fmt.Sprintf("variables.%s", k)}
multipartFilesGroups = append(multipartFilesGroups, MultipartFilesGroup{
Files: []MultipartFile{
{
Index: i,
File: item,
},
},
})
i++
case *graphql.Upload:
// continue if it is empty
if item == nil {
continue
}
iStr := strconv.Itoa(i)
vars[k] = nil
mapping[iStr] = []string{fmt.Sprintf("variables.%s", k)}
multipartFilesGroups = append(multipartFilesGroups, MultipartFilesGroup{
Files: []MultipartFile{
{
Index: i,
File: *item,
},
},
})
i++
case []*graphql.Upload:
vars[k] = make([]struct{}, len(item))
var groupFiles []MultipartFile
for itemI, itemV := range item {
iStr := strconv.Itoa(i)
mapping[iStr] = []string{fmt.Sprintf("variables.%s.%s", k, strconv.Itoa(itemI))}
groupFiles = append(groupFiles, MultipartFile{
Index: i,
File: *itemV,
})
i++
}
multipartFilesGroups = append(multipartFilesGroups, MultipartFilesGroup{
Files: groupFiles,
IsMultiple: true,
})
}
}
return multipartFilesGroups, mapping, vars
}
func prepareMultipartFormBody(
buffer *bytes.Buffer, formFields []FormField, files []MultipartFilesGroup,
) (string, error) {
writer := multipart.NewWriter(buffer)
defer writer.Close()
// form fields
for _, field := range formFields {
fieldBody, err := json.Marshal(field.Value)
if err != nil {
return "", fmt.Errorf("encode %s: %w", field.Name, err)
}
err = writer.WriteField(field.Name, string(fieldBody))
if err != nil {
return "", fmt.Errorf("write %s: %w", field.Name, err)
}
}
// files
for _, filesGroup := range files {
for _, file := range filesGroup.Files {
part, err := writer.CreateFormFile(strconv.Itoa(file.Index), file.File.Filename)
if err != nil {
return "", fmt.Errorf("form file %w", err)
}
_, err = io.Copy(part, file.File.File)
if err != nil {
return "", fmt.Errorf("copy file %w", err)
}
}
}
if err := writer.Close(); err != nil {
return "", fmt.Errorf("writer close %w", err)
}
return writer.FormDataContentType(), nil
}
func (c *Client) do(_ context.Context, req *http.Request, _ *GQLRequestInfo, res any) error {
resp, err := c.Client.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.Header.Get("Content-Encoding") == "gzip" {
resp.Body, err = gzip.NewReader(resp.Body)
if err != nil {
return fmt.Errorf("gzip decode failed: %w", err)
}
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
return c.parseResponse(body, resp.StatusCode, res)
}
func (c *Client) parseResponse(body []byte, httpCode int, result any) error {
errResponse := &ErrorResponse{}
isOKCode := httpCode < 200 || 299 < httpCode
if isOKCode {
errResponse.NetworkError = &HTTPError{
Code: httpCode,
Message: fmt.Sprintf("Response body %s", string(body)),
}
}
// some servers return a graphql error with a non OK http code, try anyway to parse the body
if err := c.unmarshal(body, result); err != nil {
var gqlErr *GqlErrorList
if errors.As(err, &gqlErr) {
errResponse.GqlErrors = &gqlErr.Errors
} else if !isOKCode {
return err
}
}
if errResponse.HasErrors() {
return errResponse
}
return nil
}
// response is a GraphQL layer response from a handler.
type response struct {
Data json.RawMessage `json:"data"`
Errors json.RawMessage `json:"errors"`
}
func (c *Client) unmarshal(data []byte, res any) error {
resp := response{}
if err := json.Unmarshal(data, &resp); err != nil {
return fmt.Errorf("failed to decode data %s: %w", string(data), err)
}
var err error
if resp.Errors != nil && len(resp.Errors) > 0 {
// try to parse standard graphql error
err = &GqlErrorList{}
if e := json.Unmarshal(data, err); e != nil {
return fmt.Errorf("faild to parse graphql errors. Response content %s - %w", string(data), e)
}
// if ParseDataWhenErrors is true, try to parse data as well
if !c.ParseDataWhenErrors {
return err
}
}
if errData := graphqljson.UnmarshalData(resp.Data, res); errData != nil {
// if ParseDataWhenErrors is true, and we failed to unmarshal data, return the actual error
if c.ParseDataWhenErrors {
return err
}
return fmt.Errorf("failed to decode data into response %s: %w", string(data), errData)
}
return err
}
func MarshalJSON(v any) ([]byte, error) {
if v == nil {
return []byte("null"), nil
}
val := reflect.ValueOf(v)
if !val.IsValid() || (val.Kind() == reflect.Ptr && val.IsNil()) {
return []byte("null"), nil
}
return encode(val)
}
func checkImplements[I any](v reflect.Value) bool {
t := v.Type()
interfaceType := reflect.TypeOf((*I)(nil)).Elem()
return t.Implements(interfaceType) || (t.Kind() == reflect.Ptr && reflect.PointerTo(t).Implements(interfaceType))
}
// encode returns an appropriate encoder function for the provided value.
func encode(v reflect.Value) ([]byte, error) {
if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) {
return []byte("null"), nil
}
if checkImplements[graphql.Marshaler](v) {
return encodeGQLMarshaler(v.Interface())
}
if checkImplements[json.Marshaler](v) {
return encodeJsonMarshaler(v.Interface())
}
if checkImplements[encoding.TextMarshaler](v) {
return encodeTextMarshaler(v.Interface())
}
t := v.Type() // Get the type from the value
switch t.Kind() {
case reflect.Ptr:
return encodePtr(v)
case reflect.Struct:
return encodeStruct(v)
case reflect.Map:
return encodeMap(v)
case reflect.Slice:
return encodeSlice(v)
case reflect.Array:
return encodeArray(v)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return encodeInt(v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return encodeUint(v)
case reflect.String:
return encodeString(v)
case reflect.Bool:
return encodeBool(v)
case reflect.Float32, reflect.Float64:
return encodeFloat(v)
case reflect.Interface:
return encodeInterface(v)
case reflect.Invalid, reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.UnsafePointer:
panic(fmt.Sprintf("unsupported type: %s", t))
default:
panic(fmt.Sprintf("unsupported type: %s", t))
}
}
func encodeGQLMarshaler(v any) ([]byte, error) {
if v == nil {
return []byte("null"), nil
}
var buf bytes.Buffer
if val, ok := v.(graphql.Marshaler); ok {
val.MarshalGQL(&buf)
} else {
return nil, fmt.Errorf("failed to encode graphql.Marshaler: %v", v)
}
return buf.Bytes(), nil
}
func encodeJsonMarshaler(v any) ([]byte, error) {
if val, ok := v.(json.Marshaler); ok {
return val.MarshalJSON()
} else {
return nil, fmt.Errorf("failed to encode json.Marshaler: %v", v)
}
}
func encodeTextMarshaler(v any) ([]byte, error) {
if _, ok := v.(encoding.TextMarshaler); ok {
// json.Marshal uses encoding.TextMarshaler internally if the value implements it.
return json.Marshal(v)
} else {
return nil, fmt.Errorf("failed to encode encoding.TextMarshaler: %v", v)
}
}
func encodeBool(v reflect.Value) ([]byte, error) {
boolValue, err := json.Marshal(v.Bool())
if err != nil {
return nil, fmt.Errorf("failed to encode bool: %v", v)
}
return boolValue, nil
}
func encodeInt(v reflect.Value) ([]byte, error) {
return []byte(fmt.Sprintf("%d", v.Int())), nil
}
func encodeUint(v reflect.Value) ([]byte, error) {
return []byte(fmt.Sprintf("%d", v.Uint())), nil
}
func encodeFloat(v reflect.Value) ([]byte, error) {
return []byte(fmt.Sprintf("%f", v.Float())), nil
}
func encodeString(v reflect.Value) ([]byte, error) {
stringValue, err := json.Marshal(v.String())
if err != nil {
return nil, fmt.Errorf("failed to encode string: %v", v)
}
return stringValue, nil
}
type fieldInfo struct {
name string
jsonName string
omitempty bool
typ reflect.Type
}
func prepareFields(t reflect.Type) []fieldInfo {
num := t.NumField()
fields := make([]fieldInfo, 0, num)
for i := range num {
f := t.Field(i)
if f.PkgPath != "" && !f.Anonymous { // Skip unexported fields unless they are embedded
continue
}
jsonTag := f.Tag.Get("json")
if jsonTag == "-" {
continue // Skip fields explicitly marked to be ignored
}
jsonName := f.Name
if jsonTag != "" {
parts := strings.Split(jsonTag, ",")
jsonName = parts[0] // Use the name specified in the JSON tag
}
fi := fieldInfo{
name: f.Name,
jsonName: jsonName,
typ: f.Type,
}
if strings.Contains(jsonTag, "omitempty") {
fi.omitempty = true
}
fields = append(fields, fi)
}
return fields
}
func encodeStruct(v reflect.Value) ([]byte, error) {
fields := prepareFields(v.Type())
result := make(map[string]json.RawMessage)
for _, field := range fields {
fieldValue := v.FieldByName(field.name)
if !fieldValue.IsValid() || (fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil()) {
continue // Skip invalid or nil pointers to avoid panics
}
if field.omitempty && fieldValue.IsZero() {
continue // Skip nil fields marked with omitempty
}
encodedValue, err := encode(fieldValue)
if err != nil {
return nil, err
}
result[field.jsonName] = encodedValue
}
return json.Marshal(result)
}
func trimQuotes(s string) string {
if len(s) > 1 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}
func encodeMap(v reflect.Value) ([]byte, error) {
result := make(map[string]json.RawMessage)
for _, key := range v.MapKeys() {
encodedKey, err := encode(key)
if err != nil {
return nil, err
}
keyStr := string(encodedKey)
keyStr = trimQuotes(keyStr)
value := v.MapIndex(key)
encodedValue, err := encode(value)
if err != nil {
return nil, err
}
result[keyStr] = encodedValue
}
return json.Marshal(result)
}
func encodeSlice(v reflect.Value) ([]byte, error) {
result := make([]json.RawMessage, v.Len())
for i := range v.Len() {
encodedValue, err := encode(v.Index(i))
if err != nil {
return nil, err
}
result[i] = encodedValue
}
return json.Marshal(result)
}
func encodeArray(v reflect.Value) ([]byte, error) {
result := make([]json.RawMessage, v.Len())
for i := range v.Len() {
encodedValue, err := encode(v.Index(i))
if err != nil {
return nil, err
}
result[i] = encodedValue
}
return json.Marshal(result)
}
func encodePtr(v reflect.Value) ([]byte, error) {
if v.IsNil() {
return []byte("null"), nil
}
return encode(v.Elem())
}
func encodeInterface(v reflect.Value) ([]byte, error) {
if v.IsNil() {
return []byte("null"), nil
}
actualValue := v.Elem()
return encode(actualValue)
}