forked from labd/commercetools-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
326 lines (280 loc) · 8.27 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
package commercetools
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
// Version identifies the current library version. Should match the git tag
const Version = "0.1.0"
type ClientEndpoints struct {
Auth string
API string
MerchantCenterAPI string
}
type ClientCredentials struct {
ClientID string
ClientSecret string
Scopes []string
}
type ClientConfig struct {
ProjectKey string
Endpoints *ClientEndpoints
Credentials *ClientCredentials
HTTPClient *http.Client
LibraryName string
LibraryVersion string
ContactURL string
ContactEmail string
}
// Config is used to pass settings for creating a new Client object
type Config struct {
ProjectKey string
URL string
HTTPClient *http.Client
LibraryName string
LibraryVersion string
ContactURL string
ContactEmail string
}
// Client bundles the logic for sending requests to the CommerceTools platform.
type Client struct {
httpClient *http.Client
url string
endpoints ClientEndpoints
projectKey string
logLevel int
userAgent string
}
// NewClient creates a new client based on the provided ClientConfig
func NewClient(cfg *ClientConfig) (*Client, error) {
if cfg.Endpoints == nil {
cfg.Endpoints = &ClientEndpoints{
Auth: os.Getenv("CTP_AUTH_URL"),
API: os.Getenv("CTP_API_URL"),
MerchantCenterAPI: os.Getenv("CTP_MC_API_URL"),
}
}
if cfg.Credentials == nil {
cfg.Credentials = &ClientCredentials{
ClientID: os.Getenv("CTP_CLIENT_ID"),
ClientSecret: os.Getenv("CTP_CLIENT_SECRET"),
Scopes: strings.Split(os.Getenv("CTP_SCOPES"), ","),
}
}
auth := &clientcredentials.Config{
ClientID: cfg.Credentials.ClientID,
ClientSecret: cfg.Credentials.ClientSecret,
Scopes: cfg.Credentials.Scopes,
TokenURL: cfg.Endpoints.Auth,
}
// If a custom httpClient is passed use that
var httpClient *http.Client
if cfg.HTTPClient != nil {
httpClient = auth.Client(
context.WithValue(oauth2.NoContext, oauth2.HTTPClient, cfg.HTTPClient))
} else {
httpClient = auth.Client(context.TODO())
}
client := &Client{
projectKey: getConfigValue(cfg.ProjectKey, "CTP_PROJECT_KEY"),
endpoints: *cfg.Endpoints,
httpClient: httpClient,
userAgent: GetUserAgent(cfg),
}
if os.Getenv("CTP_DEBUG") != "" {
client.logLevel = 1
}
return client, nil
}
func NewClientEndpoints(region string, provider string) *ClientEndpoints {
return &ClientEndpoints{
Auth: fmt.Sprintf("https://auth.%s.%s.commercetools.com/oauth/token", region, provider),
API: fmt.Sprintf("https://api.%s.%s.commercetools.com", region, provider),
MerchantCenterAPI: fmt.Sprintf("https://mc-api.%s.%s.commercetools.com", region, provider),
}
}
// New creates a new client based on the provided Config (Deprecated)
func New(cfg *Config) *Client {
userAgent := GetUserAgent(&ClientConfig{
LibraryName: cfg.LibraryName,
LibraryVersion: cfg.LibraryVersion,
ContactURL: cfg.ContactURL,
ContactEmail: cfg.ContactEmail,
})
apiURL, err := cleanURL(getConfigValue(cfg.URL, "CTP_API_URL"))
if err != nil {
return nil
}
client := &Client{
projectKey: getConfigValue(cfg.ProjectKey, "CTP_PROJECT_KEY"),
url: apiURL,
httpClient: cfg.HTTPClient,
userAgent: userAgent,
}
if client.httpClient == nil {
auth := &clientcredentials.Config{
ClientID: os.Getenv("CTP_CLIENT_ID"),
ClientSecret: os.Getenv("CTP_CLIENT_SECRET"),
Scopes: strings.Split(os.Getenv("CTP_SCOPES"), ","),
TokenURL: os.Getenv("CTP_AUTH_URL"),
}
client.httpClient = auth.Client(context.TODO())
}
client.endpoints = ClientEndpoints{
API: getConfigValue(cfg.URL, "CTP_API_URL"),
}
if os.Getenv("CTP_DEBUG") != "" {
client.logLevel = 1
}
return client
}
func getConfigValue(value string, envName string) string {
if value != "" {
return value
}
return os.Getenv(envName)
}
func (c *Client) Endpoints() ClientEndpoints {
return c.endpoints
}
func (c *Client) ProjectKey() string {
return c.projectKey
}
// Get accomodates get requests tot the CommerceTools platform.
func (c *Client) get(ctx context.Context, endpoint string, queryParams url.Values, output interface{}) error {
err := c.doRequest(ctx, "GET", endpoint, queryParams, nil, output)
return err
}
// Query accomodates query requests tot the CommerceTools platform.
func (c *Client) query(ctx context.Context, endpoint string, queryParams url.Values, output interface{}) error {
err := c.doRequest(ctx, "GET", endpoint, queryParams, nil, output)
return err
}
// Create accomodates post intended for creation requests tot the CommerceTools
// platform.
func (c *Client) create(ctx context.Context, endpoint string, queryParams url.Values, input interface{}, output interface{}) error {
data, err := serializeInput(input)
if err != nil {
return err
}
err = c.doRequest(ctx, "POST", endpoint, queryParams, data, output)
return err
}
// Update accomodates post requests intended for updates tot the CommerceTools
// platform.
func (c *Client) update(ctx context.Context, endpoint string, queryParams url.Values, version int, actions interface{}, output interface{}) error {
data, err := serializeInput(&map[string]interface{}{
"version": version,
"actions": actions,
})
if err != nil {
return err
}
err = c.doRequest(ctx, "POST", endpoint, queryParams, data, output)
return err
}
// Delete accomodates delete requests tot the CommerceTools platform.
func (c *Client) delete(ctx context.Context, endpoint string, queryParams url.Values, output interface{}) error {
err := c.doRequest(ctx, "DELETE", endpoint, queryParams, nil, output)
return err
}
func (c *Client) doRequest(ctx context.Context, method string, endpoint string, params url.Values, data io.Reader, output interface{}) error {
url := c.endpoints.API + "/" + c.projectKey + "/" + endpoint
resp, err := c.getResponse(ctx, method, url, params, data, nil)
if err != nil {
return err
}
return processResponse(resp, output)
}
func (c *Client) getResponse(ctx context.Context, method string, url string, params url.Values, data io.Reader, headers map[string]string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, method, url, data)
if err != nil {
return nil, errors.Wrap(err, "Creating new request")
}
if params != nil {
req.URL.RawQuery = params.Encode()
}
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("User-Agent", c.userAgent)
for headerName, headerValue := range headers {
req.Header.Set(headerName, headerValue)
}
if c.logLevel > 0 {
logRequest(req)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, handleAuthError(err)
}
if c.logLevel > 0 {
logResponse(resp)
}
return resp, nil
}
func processResponse(resp *http.Response, output interface{}) error {
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
switch resp.StatusCode {
case 200, 201:
err := json.Unmarshal(body, output)
return err
default:
if resp.StatusCode == 404 && len(body) == 0 {
return ErrorResponse{
StatusCode: resp.StatusCode,
Message: "Not Found (404): ResourceNotFound",
}
}
customErr := ErrorResponse{}
err = json.Unmarshal(body, &customErr)
if err != nil {
return err
}
return customErr
}
}
func cleanURL(baseURL string) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return baseURL, err
}
u.Path = ""
return u.String(), nil
}
func serializeInput(input interface{}) (io.Reader, error) {
m, err := json.MarshalIndent(input, "", "\t")
if err != nil {
return nil, errors.Wrap(err, "Unable to serialize content")
}
data := bytes.NewReader(m)
return data, nil
}
// Unnwrap the error object and return an ErrorResponse
func handleAuthError(err error) error {
if uErr, ok := err.(*url.Error); ok {
if rErr, ok := uErr.Err.(*oauth2.RetrieveError); ok {
customErr := ErrorResponse{}
if len(rErr.Body) > 0 {
jsonErr := json.Unmarshal(rErr.Body, &customErr)
if jsonErr != nil {
return jsonErr
}
} else {
customErr.Message = rErr.Error()
}
return customErr
}
}
return err
}