-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
323 lines (272 loc) · 7.49 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
package trustpilot
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"time"
"golang.org/x/oauth2"
)
var (
// Compile time check whether Client value implements Trustpilot interface.
_ Trustpilot = (*Client)(nil)
ErrNotFound = errors.New("NOT_FOUND")
ErrInvalidArgument = errors.New("INVALID_ARGUMENT")
ErrInternal = errors.New("INTERNAL")
ErrUnauthenticated = errors.New("UNAUTHENTICATED")
apiBaseURL = &url.URL{
Host: "api.trustpilot.com",
Scheme: "https",
Path: "/v1/",
}
invitationAPIBaseURL = &url.URL{
Host: "invitations-api.trustpilot.com",
Scheme: "https",
Path: "/v1/",
}
tokenURL = &url.URL{
Host: "api.trustpilot.com",
Scheme: "https",
Path: "/v1/oauth/oauth-business-users-for-applications/accesstoken",
}
)
const (
invitationPathf = "private/business-units/%s/email-invitations"
)
// PasswordGrantConfig configuration for the oauth2 password grant type. Use
// TokenURL client option to set oauth2 token url.
type PasswordGrantConfig struct {
ClientID string
ClientSecret string
Username string
Password string
}
// ClientOption is a functional option for configuring the API client.
type ClientOption func(*Client) error
// APIBaseURL allows to change the default API base url.
func APIBaseURL(u *url.URL) ClientOption {
return func(c *Client) error {
c.apiBaseURL = u
return nil
}
}
// TokenURL allows to change the default API oauth 2.0 token url.
func TokenURL(u *url.URL) ClientOption {
return func(c *Client) error {
c.tokenURL = u
return nil
}
}
// InvitationAPIBaseURL allows to change the default Invitation API base url.
func InvitationAPIBaseURL(u *url.URL) ClientOption {
return func(c *Client) error {
c.invitationAPIBaseURL = u
return nil
}
}
// AuthConfig is a functional option for configuring oauth 2.0 password grant credentials.
func AuthConfig(conf *PasswordGrantConfig) ClientOption {
return func(c *Client) error {
c.authConfig = conf
return nil
}
}
// Debug is a functional option for configuring client debug.
func Debug(b bool) ClientOption {
return func(c *Client) error {
c.debug = b
return nil
}
}
// HTTPClient is a functional option for configuring http client.
func HTTPClient(h *http.Client) ClientOption {
return func(c *Client) error {
c.httpClient = h
return nil
}
}
func (c *Client) applyOptions(opts ...ClientOption) error {
for _, o := range opts {
if err := o(c); err != nil {
return err
}
}
return nil
}
// Client implements Trustpilot API.
type Client struct {
debug bool
apiBaseURL *url.URL
invitationAPIBaseURL *url.URL
tokenURL *url.URL
authConfig *PasswordGrantConfig
tokenSource oauth2.TokenSource
httpClient *http.Client
}
// NewClient sets up a new Trustpilot client.
func NewClient(opts ...ClientOption) (*Client, error) {
c := &Client{
apiBaseURL: apiBaseURL,
invitationAPIBaseURL: invitationAPIBaseURL,
tokenURL: tokenURL,
httpClient: &http.Client{
Timeout: time.Second * 30,
},
}
if err := c.applyOptions(opts...); err != nil {
return nil, err
}
// Assume authentication is not required for the API.
if c.authConfig == nil {
return c, nil
}
// Set up oauth2 password grant flow.
oauthConfig := &oauth2.Config{
ClientID: c.authConfig.ClientID,
ClientSecret: c.authConfig.ClientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: c.tokenURL.String(),
},
}
t, err := oauthConfig.PasswordCredentialsToken(context.Background(), c.authConfig.Username, c.authConfig.Password)
if err != nil {
return nil, err
}
c.tokenSource = oauth2.ReuseTokenSource(t, oauthConfig.TokenSource(context.Background(), t))
return c, nil
}
func (c *Client) CreateInvitation(ctx context.Context, r *CreateInvitationRequest) (*CreateInvitationResponse, error) {
path := fmt.Sprintf(invitationPathf, r.BusinessUnitID)
req, err := c.newInvitationAPIRequest("POST", path, r)
if err != nil {
return nil, err
}
var res CreateInvitationResponse
if err := c.do(ctx, req, &res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) ListTemplates(ctx context.Context, r *ListTemplatesRequest) (*ListTemplatesResponse, error) {
path := fmt.Sprintf(invitationPathf, r.BusinessUnitID)
req, err := c.newInvitationAPIRequest("GET", path, r)
if err != nil {
return nil, err
}
var res ListTemplatesResponse
if err := c.do(ctx, req, &res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) newAPIRequest(method, path string, body interface{}) (*http.Request, error) {
u := c.apiBaseURL.ResolveReference(&url.URL{Path: path})
return c.newRequest(method, u, body)
}
func (c *Client) newInvitationAPIRequest(method, path string, body interface{}) (*http.Request, error) {
u := c.invitationAPIBaseURL.ResolveReference(&url.URL{Path: path})
return c.newRequest(method, u, body)
}
func (c *Client) newRequest(method string, u *url.URL, body interface{}) (*http.Request, error) {
var b []byte
if body != nil {
jb, err := json.Marshal(body)
if err != nil {
return nil, err
}
b = jb
}
req, err := http.NewRequest(method, u.String(), bytes.NewReader(b))
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.tokenSource == nil {
return req, nil
}
// Use the token for authentication.
tkn, err := c.tokenSource.Token()
if err != nil {
var e error
// Try to figure out what kind of error it is.
if rErr, ok := err.(*oauth2.RetrieveError); ok {
switch rErr.Response.StatusCode {
case http.StatusUnauthorized:
e = fmt.Errorf("%w: %s", ErrUnauthenticated, rErr.Error())
case http.StatusBadRequest:
e = fmt.Errorf("%w: %s", ErrInvalidArgument, rErr.Error())
case http.StatusNotFound:
e = fmt.Errorf("%w: %s", ErrNotFound, rErr.Error())
default:
e = fmt.Errorf("%w: %s", ErrInternal, rErr.Error())
}
}
return nil, e
}
req.Header.Set("Authorization", "Bearer "+tkn.AccessToken)
return req, nil
}
func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) error {
if c.debug {
reqDump, err := httputil.DumpRequest(req, true)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", reqDump)
}
resp, err := c.httpClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
if c.debug {
respDump, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", respDump)
}
if err := parseError(resp); err != nil {
return err
}
if resp.ContentLength != 0 && v != nil {
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return err
}
}
return nil
}
func parseError(resp *http.Response) error {
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusAccepted:
return nil
case http.StatusBadRequest, http.StatusUnprocessableEntity:
// Attempt to read error response.
var e ErrorResponse
if err := json.NewDecoder(resp.Body).Decode(&e); err != nil {
return ErrInvalidArgument
}
return fmt.Errorf("%w: %s", ErrInvalidArgument, e.Details)
case http.StatusUnauthorized:
return ErrUnauthenticated
case http.StatusNotFound:
return ErrNotFound
default:
return ErrInternal
}
}
type ErrorResponse struct {
Message string `json:"message,omitempty"`
ErrorCode int `json:"errorCode,omitempty"`
Details string `json:"details,omitempty"`
CorrelationID string `json:"correlationId,omitempty"`
}
func (r *ErrorResponse) Error() string {
return r.Message
}