forked from movio/bramble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
206 lines (171 loc) · 4.84 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
package bramble
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"strings"
"time"
"github.com/vektah/gqlparser/v2/ast"
)
// GraphQLClient is a GraphQL client.
type GraphQLClient struct {
HTTPClient *http.Client
MaxResponseSize int64
UserAgent string
}
// ClientOpt is a function used to set a GraphQL client option
type ClientOpt func(*GraphQLClient)
// NewClient creates a new GraphQLClient from the given options.
func NewClient(opts ...ClientOpt) *GraphQLClient {
return NewClientWithPlugins(nil, opts...)
}
func NewClientWithPlugins(plugins []Plugin, opts ...ClientOpt) *GraphQLClient {
c := &GraphQLClient{
HTTPClient: &http.Client{
Timeout: 5 * time.Second,
},
MaxResponseSize: 1024 * 1024,
}
for _, opt := range opts {
opt(c)
}
for _, plugin := range plugins {
c.HTTPClient.Transport = plugin.WrapGraphQLClientTransport(c.HTTPClient.Transport)
}
return c
}
func NewClientWithoutKeepAlive(opts ...ClientOpt) *GraphQLClient {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.DisableKeepAlives = true
c := &GraphQLClient{
HTTPClient: &http.Client{
Timeout: 5 * time.Second,
Transport: transport,
},
MaxResponseSize: 1024 * 1024,
}
for _, opt := range opts {
opt(c)
}
return c
}
// WithHTTPClient sets a custom HTTP client to be used when making downstream queries.
func WithHTTPClient(client *http.Client) ClientOpt {
return func(s *GraphQLClient) {
s.HTTPClient = client
}
}
// WithMaxResponseSize sets the max allowed response size. The client will only
// read up to maxResponseSize and that size is exceeded an an error will be
// returned.
func WithMaxResponseSize(maxResponseSize int64) ClientOpt {
return func(s *GraphQLClient) {
s.MaxResponseSize = maxResponseSize
}
}
// WithUserAgent set the user agent used by the client.
func WithUserAgent(userAgent string) ClientOpt {
return func(s *GraphQLClient) {
s.UserAgent = userAgent
}
}
// Request executes a GraphQL request.
func (c *GraphQLClient) Request(ctx context.Context, url string, request *Request, out interface{}) error {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(request)
if err != nil {
return fmt.Errorf("unable to encode request body: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &buf)
if err != nil {
return fmt.Errorf("unable to create request: %w", err)
}
if request.Headers != nil {
httpReq.Header = request.Headers.Clone()
}
httpReq.Header.Set("Content-Type", "application/json; charset=utf-8")
httpReq.Header.Set("Accept", "application/json; charset=utf-8")
if c.UserAgent != "" {
httpReq.Header.Set("User-Agent", c.UserAgent)
}
res, err := c.HTTPClient.Do(httpReq)
if err != nil {
return fmt.Errorf("error during request: %w", err)
}
defer res.Body.Close()
maxResponseSize := c.MaxResponseSize
if maxResponseSize == 0 {
maxResponseSize = math.MaxInt64
}
limitReader := io.LimitedReader{
R: res.Body,
N: maxResponseSize,
}
graphqlResponse := Response{
Data: out,
}
err = json.NewDecoder(&limitReader).Decode(&graphqlResponse)
if err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) {
if limitReader.N == 0 {
return fmt.Errorf("response exceeded maximum size of %d bytes", maxResponseSize)
}
}
return fmt.Errorf("error decoding response: %w", err)
}
if len(graphqlResponse.Errors) > 0 {
return graphqlResponse.Errors
}
return nil
}
// Request is a GraphQL request.
type Request struct {
Query string `json:"query"`
OperationName string `json:"operationName,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
Headers http.Header `json:"-"`
}
// NewRequest creates a new GraphQL requests from the provided body.
func NewRequest(body string) *Request {
return &Request{
Query: body,
}
}
func (r *Request) WithHeaders(headers http.Header) *Request {
r.Headers = headers
return r
}
func (r *Request) WithOperationName(operationName string) *Request {
r.OperationName = operationName
return r
}
// Response is a GraphQL response
type Response struct {
Errors GraphqlErrors `json:"errors"`
Data interface{}
}
// GraphqlErrors represents a list of GraphQL errors, as returned in a GraphQL
// response.
type GraphqlErrors []GraphqlError
// GraphqlError is a single GraphQL error
type GraphqlError struct {
Message string `json:"message"`
Path ast.Path `json:"path,omitempty"`
Extensions map[string]interface{} `json:"extensions"`
}
// Error returns a string representation of the error list
func (e GraphqlErrors) Error() string {
var errs []string
for _, err := range e {
errs = append(errs, err.Message)
}
return strings.Join(errs, ",")
}
func GenerateUserAgent(operation string) string {
return fmt.Sprintf("Bramble/%s (%s)", Version, operation)
}