-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
282 lines (222 loc) · 7.91 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
package goarpa
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/erfandiakoo/goarpa/v2/shared/constant"
"github.com/go-resty/resty/v2"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
)
type GoArpa struct {
basePath string
restyClient *resty.Client
Config struct {
GetServiceTokenEndpoint string
CreateCustomerEndpoint string
CreateTransactionEndpoint string
CreateServiceEndpoint string
GetCustomerEndpoint string
GetItemEndpoint string
}
}
const (
adminClientID string = "admin-cli"
urlSeparator string = "/"
)
func makeURL(path ...string) string {
return strings.Join(path, urlSeparator)
}
// GetRequest returns a request for calling endpoints.
func (g *GoArpa) GetRequest(ctx context.Context) *resty.Request {
var err HTTPErrorResponse
return injectTracingHeaders(
ctx, g.restyClient.R().
SetContext(ctx).
SetError(&err),
)
}
func injectTracingHeaders(ctx context.Context, req *resty.Request) *resty.Request {
// look for span in context, do nothing if span is not found
span := opentracing.SpanFromContext(ctx)
if span == nil {
return req
}
// look for tracer in context, use global tracer if not found
tracer, ok := ctx.Value(tracerContextKey).(opentracing.Tracer)
if !ok || tracer == nil {
tracer = opentracing.GlobalTracer()
}
// inject tracing header into request
err := tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
if err != nil {
return req
}
return req
}
// GetRequestWithBearerAuthNoCache returns a JSON base request configured with an auth token and no-cache header.
func (g *GoArpa) GetRequestWithBearerAuthNoCache(ctx context.Context, token string) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json").
SetHeader("Cache-Control", "no-cache")
}
// GetRequestWithBearerAuth returns a JSON base request configured with an auth token.
func (g *GoArpa) GetRequestWithBearerAuth(ctx context.Context, token string) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json")
}
func (g *GoArpa) GetRequestWithBearerAuthWithCookie(ctx context.Context, token string, cookie []*http.Cookie) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetCookie(cookie[0]).
SetHeader("Content-Type", "application/json")
}
func NewClient(basePath string, options ...func(*GoArpa)) *GoArpa {
c := GoArpa{
basePath: strings.TrimRight(basePath, urlSeparator),
restyClient: resty.New(),
}
c.Config.GetServiceTokenEndpoint = makeURL("serv", "token", "GetServiceToken")
c.Config.CreateCustomerEndpoint = makeURL("serv", "api", "PostBusiness")
c.Config.CreateTransactionEndpoint = makeURL("serv", "api", "NewTransaction")
c.Config.CreateServiceEndpoint = makeURL("serv", "api", "PostService")
c.Config.GetCustomerEndpoint = makeURL("serv", "api", "GetBusiness")
c.Config.GetItemEndpoint = makeURL("serv", "api", "GetItem")
for _, option := range options {
option(&c)
}
return &c
}
// RestyClient returns the internal resty g.
// This can be used to configure the g.
func (g *GoArpa) RestyClient() *resty.Client {
return g.restyClient
}
// SetRestyClient overwrites the internal resty g.
func (g *GoArpa) SetRestyClient(restyClient *resty.Client) {
g.restyClient = restyClient
}
func checkForError(resp *resty.Response, err error, errMessage string) error {
if err != nil {
return &APIError{
Code: 0,
Message: errors.Wrap(err, errMessage).Error(),
Type: ParseAPIErrType(err),
}
}
if resp == nil {
return &APIError{
Message: "empty response",
Type: ParseAPIErrType(err),
}
}
if resp.IsError() {
var msg string
if e, ok := resp.Error().(*HTTPErrorResponse); ok && e.NotEmpty() {
msg = fmt.Sprintf("%s: %s", resp.Status(), e)
} else {
msg = resp.Status()
}
return &APIError{
Code: resp.StatusCode(),
Message: msg,
Type: ParseAPIErrType(err),
}
}
return nil
}
func (g *GoArpa) GetAdminToken(ctx context.Context, username string, password string) (string, []*http.Cookie, error) {
const errMessage = "could not get token"
req := g.GetRequest(ctx)
resp, err := req.SetQueryParams(map[string]string{
"username": username,
"password": password,
}).
Get(g.basePath + "/" + g.Config.GetServiceTokenEndpoint + "?")
if err := checkForError(resp, err, errMessage); err != nil {
return "", nil, err
}
return resp.String(), resp.Cookies(), nil
}
func (g *GoArpa) CreateCustomer(ctx context.Context, accessToken string, cookie []*http.Cookie, customer CreateCustomerRequest) (*RetCustomerResponse, error) {
const errMessage = "could not create customer"
var response RetCustomerResponse
resp, err := g.GetRequestWithBearerAuthWithCookie(ctx, accessToken, cookie).
SetBody(customer).
SetResult(&response).
Post(g.basePath + "/" + g.Config.CreateCustomerEndpoint)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &response, nil
}
func (g *GoArpa) CreateTransaction(ctx context.Context, accessToken string, transaction CreateTransactionRequest) (*CreateTransactionResponse, error) {
const errMessage = "could not create transaction"
var response CreateTransactionResponse
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetBody(transaction).
SetResult(response).
Post(g.basePath + "/" + g.Config.CreateTransactionEndpoint)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &response, nil
}
func (g *GoArpa) CreateService(ctx context.Context, accessToken string, service CreateServiceRequest) (*CreateServiceResponse, error) {
const errMessage = "could not create service"
var response CreateServiceResponse
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetBody(service).
SetResult(response).
Post(g.basePath + "/" + g.Config.CreateServiceEndpoint)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &response, nil
}
func (g *GoArpa) GetCustomerByMobile(ctx context.Context, accessToken string, cookie []*http.Cookie, mobile string) (*GetCustomerResponse, error) {
const errMessage = "could not get customer info"
// Create an instance of GetCustomerResponse to hold the response
result := &GetCustomerResponse{}
// Make the request and set result to auto-unmarshal
resp, err := g.GetRequestWithBearerAuthWithCookie(ctx, accessToken, cookie).
SetQueryParam(constant.MobileKey, mobile).
SetResult(result).
Get(fmt.Sprintf("%s/%s", g.basePath, g.Config.GetCustomerEndpoint))
// Check for errors
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
// Return the unmarshaled result
return result, nil
}
func (g *GoArpa) GetCustomerByBusinessCode(ctx context.Context, accessToken string, cookie []*http.Cookie, businessCode string) (*GetCustomerResponse, error) {
const errMessage = "could not get customer info"
result := &GetCustomerResponse{}
resp, err := g.GetRequestWithBearerAuthWithCookie(ctx, accessToken, cookie).
SetQueryParam(constant.BusinessCodeKey, businessCode).
SetResult(result).
Get(fmt.Sprintf("%s/%s", g.basePath, g.Config.GetCustomerEndpoint))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return result, nil
}
func (g *GoArpa) GetServiceByItemCode(ctx context.Context, accessToken string, cookie []*http.Cookie, itemCode string) (*RetServiceResponse, error) {
const errMessage = "could not get service info"
result := &RetServiceResponse{}
// Make the request and set result to auto-unmarshal
resp, err := g.GetRequestWithBearerAuthWithCookie(ctx, accessToken, cookie).
SetQueryParam(constant.ItemCodeKey, itemCode).
SetResult(&result).
Get(fmt.Sprintf("%s/%s", g.basePath, g.Config.GetItemEndpoint))
// Check for errors
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
// Return the unmarshaled result
return result, nil
}