forked from gqlgo/gqlgenc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
268 lines (222 loc) · 7.67 KB
/
Copy pathclient.go
File metadata and controls
268 lines (222 loc) · 7.67 KB
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
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/aws/aws-sdk-go/aws"
session "github.com/aws/aws-sdk-go/aws/session"
cognito "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/perchcredit/gqlgenc/graphqljson"
"github.com/perchcredit/gqlgenc/introspection"
"github.com/vektah/gqlparser/v2/gqlerror"
"golang.org/x/xerrors"
)
// HTTPRequestOption represents the options applicable to the http client
type HTTPRequestOption func(req *http.Request)
// ----- Client ---------------------------------------------------
// Client is the http client wrapper
type Client struct {
BaseURL string
Client *http.Client
HTTPRequestOptions []HTTPRequestOption
Authorization ClientAuthorization
}
type ClientAuthorization struct {
CognitoIdentityProvider *cognito.CognitoIdentityProvider
ClientID string
UserPoolID string
Username string
Password string
}
// Request represents an outgoing GraphQL request
type Request struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}
// ----- Client Initialization Options ----------------------------
type ClientOptions struct {
HTTPClient *http.Client
HTTPRequestOptions []HTTPRequestOption
BaseURL string
AuthorizationOptions ClientAuthorizationOptions
}
type ClientAuthorizationOptions struct {
Session *session.Session
ClientID string
UserPoolID string
Username string
Password string
}
// ----- Client Constructor ----------------------------------------
// NewClient creates a new http client wrapper
func NewClient(options ClientOptions) *Client {
// Create base client authorization
authorization := ClientAuthorization{
UserPoolID: options.AuthorizationOptions.UserPoolID,
ClientID: options.AuthorizationOptions.ClientID,
Username: options.AuthorizationOptions.Username,
Password: options.AuthorizationOptions.Password,
}
// If authorization options is provided
// Fill authorization
if options.AuthorizationOptions.Session != nil {
authorization.CognitoIdentityProvider = cognito.New(options.AuthorizationOptions.Session)
}
return &Client{
Client: options.HTTPClient,
HTTPRequestOptions: options.HTTPRequestOptions,
BaseURL: options.BaseURL,
Authorization: authorization,
}
}
func (c *Client) newRequest(ctx context.Context, operationName, query string, vars map[string]interface{}, httpRequestOptions []HTTPRequestOption) (*http.Request, error) {
// Create request object
// Fill query
// Fill variables
r := &Request{
Query: query,
Variables: vars,
}
// Marshal request body
// Exit on error
requestBody, err := json.Marshal(r)
if err != nil {
return nil, xerrors.Errorf("encode: %w", err)
}
// Create new request
// Exit on error
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL, bytes.NewBuffer(requestBody))
if err != nil {
return nil, xerrors.Errorf("create request struct failed: %w", err)
}
// If query is not introspection query
// Add appropriate authorization headers
if query != introspection.Introspection {
// Login with cognito admin credentials
// Exit on error
login, err := c.Authorization.CognitoIdentityProvider.AdminInitiateAuth(&cognito.AdminInitiateAuthInput{
AuthFlow: aws.String("ADMIN_USER_PASSWORD_AUTH"),
ClientId: &c.Authorization.ClientID,
UserPoolId: &c.Authorization.UserPoolID,
AuthParameters: map[string]*string{
"USERNAME": aws.String(c.Authorization.Username),
"PASSWORD": aws.String(c.Authorization.Password),
},
})
if err != nil {
return nil, xerrors.Errorf("failed to login : %w", err)
}
// If authentication result is successful and id token can be parsed
// Add in authentication header
if login != nil && login.AuthenticationResult != nil && login.AuthenticationResult.IdToken != nil {
req.Header.Add("Authorization", "Bearer "+*login.AuthenticationResult.IdToken)
}
}
// Add HTTP Options
for _, httpRequestOption := range c.HTTPRequestOptions {
httpRequestOption(req)
}
for _, httpRequestOption := range httpRequestOptions {
httpRequestOption(req)
}
return req, nil
}
// 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)
}
// Post sends a http POST request to the graphql endpoint with the given query then unpacks
// the response into the given object.
func (c *Client) Post(ctx context.Context, operationName, query string, respData interface{}, vars map[string]interface{}, httpRequestOptions ...HTTPRequestOption) error {
req, err := c.newRequest(ctx, operationName, query, vars, httpRequestOptions)
if err != nil {
return xerrors.Errorf("don't create request: %w", err)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
resp, err := c.Client.Do(req)
if err != nil {
return xerrors.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return xerrors.Errorf("failed to read response body: %w", err)
}
return parseResponse(body, resp.StatusCode, respData)
}
func parseResponse(body []byte, httpCode int, result interface{}) error {
errResponse := &ErrorResponse{}
isKOCode := httpCode < 200 || 299 < httpCode
if isKOCode {
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 := unmarshal(body, result); err != nil {
if gqlErr, ok := err.(*GqlErrorList); ok {
errResponse.GqlErrors = &gqlErr.Errors
} else if !isKOCode { // if is KO code there is already the http error, this error should not be returned
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 unmarshal(data []byte, res interface{}) error {
resp := response{}
if err := json.Unmarshal(data, &resp); err != nil {
return xerrors.Errorf("failed to decode data %s: %w", string(data), err)
}
if resp.Errors != nil && len(resp.Errors) > 0 {
// try to parse standard graphql error
errors := &GqlErrorList{}
if e := json.Unmarshal(data, errors); e != nil {
return xerrors.Errorf("faild to parse graphql errors. Response content %s - %w ", string(data), e)
}
return errors
}
if err := graphqljson.UnmarshalData(resp.Data, res); err != nil {
return xerrors.Errorf("failed to decode data into response %s: %w", string(data), err)
}
return nil
}