-
Notifications
You must be signed in to change notification settings - Fork 0
/
restClient.go
305 lines (237 loc) · 7.63 KB
/
restClient.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
package eventuate
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/go-resty/resty"
"crypto/tls"
loglib "github.com/eventuate-clients/eventuate-client-golang/logger"
)
type RESTClient struct {
Credentials *Credentials
Url *url.URL
ll loglib.LogLevelEnum
lg loglib.Logger
typeHints typeHintsMap
resty *resty.Client
}
func NewRESTClient(credentials *Credentials, serverUrl string) (*RESTClient, error) {
if credentials == nil {
return nil, AppError("NewRESTClient: Credentials not provided")
}
if len(serverUrl) == 0 {
return nil, AppError("NewRESTClient: url not provided")
}
storeServerUrl, urlErr := url.Parse(serverUrl)
if urlErr != nil {
return nil, urlErr
}
var rest *RESTClient
retryOnUnavailability := resty.RetryConditionFunc(func(resp *resty.Response) (bool, error) {
status := resp.StatusCode()
switch status {
case http.StatusOK:
return false, nil
case http.StatusServiceUnavailable:
fallthrough
case http.StatusRequestTimeout:
return true, nil
}
return false, rest.handleNon200Code(status, storeServerUrl, resp.Request.Body, resp.Body())
})
restyClient := resty.
SetHeader("Content-Type", "application/json").
SetBasicAuth(credentials.apiKeyId, credentials.apiKeySecret).
AddRetryCondition(retryOnUnavailability)
rest = &RESTClient{
Credentials: credentials,
Url: storeServerUrl,
ll: loglib.Silent,
lg: loglib.NewNilLogger(),
resty: restyClient,
typeHints: NewTypeHintsMap()}
return rest, nil
}
func (rest *RESTClient) SetLogLevel(level loglib.LogLevelEnum) {
rest.lg = loglib.NewLogger(level)
rest.ll = level
}
func (rest *RESTClient) SetInsecureSkipVerify(flag bool) {
rest.resty.SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: flag})
}
func (rest *RESTClient) Find(
aggregateType string,
entityId Int128,
findOptions *AggregateCrudFindOptions) (*LoadedEvents, error) {
rest.lg.Printf("Find(type: %s, entityId: %s)", aggregateType, entityId)
query := url.Values{}
if findOptions != nil {
if findOptions.TriggeringEvent != nil {
query["triggeringEventToken"] = []string{findOptions.TriggeringEvent.String()}
}
}
reqUrl, parseErr := rest.Url.Parse(makeGetUrl(rest.Credentials.Space, aggregateType, entityId.String(), query.Encode()))
if parseErr != nil {
rest.lg.Println(parseErr)
return nil, parseErr
}
resp, respErr := rest.resty.R().Get(reqUrl.String())
if respErr != nil {
rest.lg.Println(respErr)
return nil, respErr
}
status := resp.StatusCode()
body := resp.Body()
rest.lg.Printf("\nFIND:\nURL: %s\nHEADERS: %v\nRESPONSE: %v\n",
reqUrl, resp.Request.Header, string(body))
if status == http.StatusOK {
return rest.handleGetResponse(body)
}
return nil, rest.handleNon200Code(status, reqUrl, resp.Request.Body, body)
}
func (rest *RESTClient) Save(aggregateType string,
events []EventTypeAndData,
saveOptions *AggregateCrudSaveOptions) (*EntityIdVersionAndEventIds, error) {
rest.lg.Printf("Save(type: %s, events: %s)", aggregateType, events)
jsonPayload := make(map[string]interface{})
jsonPayload["entityTypeName"] = aggregateType
jsonPayload["events"] = events
if saveOptions != nil {
if !saveOptions.EntityId.IsNil() {
jsonPayload["entityId"] = saveOptions.EntityId
}
}
reqUrl, parseErr := rest.Url.Parse(makeNsUrl(rest.Credentials.Space))
if parseErr != nil {
rest.lg.Println(parseErr)
return nil, parseErr
}
reqJson, reqJsonErr := json.Marshal(jsonPayload)
if reqJsonErr != nil {
rest.lg.Println(reqJsonErr)
return nil, reqJsonErr
}
reqJsonTxt := string(reqJson)
resp, respErr := rest.resty.R().SetBody(jsonPayload).Post(reqUrl.String())
if respErr != nil {
rest.lg.Println(respErr)
return nil, respErr
}
status := resp.StatusCode()
body := resp.Body()
rest.lg.Printf("\nSAVE:\nURL: %s\nBODY: %v\n(%v) \nHEADERS: %v\nRESPONSE: %v\n",
reqUrl, reqJsonTxt, jsonPayload, resp.Request.Header, string(body))
if status == http.StatusOK {
return rest.handleCreateResponse(body)
}
return nil, rest.handleNon200Code(status, reqUrl, resp.Request.Body, body)
}
func (rest *RESTClient) Update(
aggregateIdAndType EntityIdAndType,
entityVersion Int128,
events []EventTypeAndData,
updateOptions *AggregateCrudUpdateOptions) (*EntityIdVersionAndEventIds, error) {
rest.lg.Printf("Update(type: %s, events: %s)", aggregateIdAndType, events)
jsonPayload := make(map[string]interface{})
jsonPayload["entityVersion"] = entityVersion
jsonPayload["events"] = events
if updateOptions != nil {
if updateOptions.TriggeringEvent != nil {
jsonPayload["triggeringEventToken"] = *updateOptions.TriggeringEvent
}
}
reqUrl, parseErr := rest.Url.Parse(makeUpdateUrl(rest.Credentials.Space, aggregateIdAndType))
if parseErr != nil {
rest.lg.Println(parseErr)
return nil, parseErr
}
reqJson, reqJsonErr := json.Marshal(jsonPayload)
if reqJsonErr != nil {
rest.lg.Println(reqJsonErr)
return nil, reqJsonErr
}
reqJsonTxt := string(reqJson)
resp, respErr := rest.resty.R().SetBody(jsonPayload).Post(reqUrl.String())
if respErr != nil {
rest.lg.Println(respErr)
return nil, respErr
}
status := resp.StatusCode()
body := resp.Body()
rest.lg.Printf("\nUPDATE:\nURL: %s\nBODY: %v\n(%v) \nHEADERS: %v\nRESPONSE: %v\n",
reqUrl, reqJsonTxt, jsonPayload, resp.Request.Header, string(body))
if status == http.StatusOK {
return rest.handleUpdateResponse(body)
}
return nil, rest.handleNon200Code(status, reqUrl, resp.Request.Body, body)
}
func makeNsUrl(space string) string {
if len(space) == 0 {
space = "default"
}
return fmt.Sprintf("/entity/%s", space)
}
func makeUpdateUrl(space string, idAndType EntityIdAndType) string {
return fmt.Sprintf("%s/%s/%s", makeNsUrl(space), idAndType.EntityType, idAndType.EntityId)
}
func makeGetUrl(space, aggType, entityId, query string) string {
return fmt.Sprintf("%s/%s/%s?%s", makeNsUrl(space), aggType, entityId, query)
}
func (rest *RESTClient) handleNon200Code(code int, reqUrl *url.URL, reqBody interface{}, respBody []byte) error {
var conflict string
if code == http.StatusConflict {
var (
jsMap map[string]interface{}
)
jsMap = make(map[string]interface{})
jsonErr := json.Unmarshal(respBody, &jsMap)
if jsonErr == nil {
errorProp, isString := jsMap["Error"].(string)
if isString {
conflict = errorProp
}
}
}
return RestError(code, conflict, "URL: %s\nRequest: %#v\nResponse: %v", reqUrl, reqBody, string(respBody))
}
func (rest *RESTClient) handleGetResponse(respBody []byte) (*LoadedEvents, error) {
var response GetResponse
err := json.Unmarshal(respBody, &response)
if err != nil {
return nil, err
}
tmp := LoadedEvents(response)
if rest.ll != loglib.Silent {
o, _ := json.Marshal(tmp)
rest.lg.Printf("handleGetResponse() result: <LoadedEvents: %v />\n", string(o))
}
return &tmp, nil
}
func (rest *RESTClient) handleCreateResponse(respBody []byte) (*EntityIdVersionAndEventIds, error) {
var response CreateResponse
err := json.Unmarshal(respBody, &response)
if err != nil {
return nil, err
}
tmp := EntityIdVersionAndEventIds(response)
if rest.ll != loglib.Silent {
o, _ := json.Marshal(tmp)
rest.lg.Printf("handleCreateResponse() result: <EntityIdVersionAndEventIds: %v />\n", string(o))
}
return &tmp, nil
}
func (rest *RESTClient) handleUpdateResponse(respBody []byte) (*EntityIdVersionAndEventIds, error) {
var response UpdateResponse
err := json.Unmarshal(respBody, &response)
if err != nil {
return nil, err
}
tmp := EntityIdVersionAndEventIds(response)
if rest.ll != loglib.Silent {
o, _ := json.Marshal(tmp)
rest.lg.Printf("handleUpdateResponse() result: <EntityIdVersionAndEventIds: %v />\n", string(o))
}
return &tmp, nil
}