From 3043f672149339cdd823264abc07ee3d5d78aba3 Mon Sep 17 00:00:00 2001 From: gabs Date: Wed, 28 Feb 2024 21:15:28 -0300 Subject: [PATCH 01/19] Refactor request built way --- pkg/internal/baseclient/client.go | 191 ----------------------- pkg/internal/baseclient/client_option.go | 27 ---- pkg/internal/baseclient/client_test.go | 190 ---------------------- pkg/internal/httpclient/helper.go | 160 +++++++++++++++++++ 4 files changed, 160 insertions(+), 408 deletions(-) delete mode 100644 pkg/internal/baseclient/client.go delete mode 100644 pkg/internal/baseclient/client_option.go delete mode 100644 pkg/internal/baseclient/client_test.go create mode 100644 pkg/internal/httpclient/helper.go diff --git a/pkg/internal/baseclient/client.go b/pkg/internal/baseclient/client.go deleted file mode 100644 index 8da1d254..00000000 --- a/pkg/internal/baseclient/client.go +++ /dev/null @@ -1,191 +0,0 @@ -package baseclient - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "runtime" - "strings" - - "github.com/google/uuid" - "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/httpclient" -) - -const ( - currentSDKVersion string = "x.x.x" - productID string = "abc" -) - -var ( - userAgent = fmt.Sprintf("MercadoPago Go SDK/%s", currentSDKVersion) - trackingID = fmt.Sprintf("platform:%s,type:SDK%s,so;", runtime.Version(), currentSDKVersion) -) - -// Get makes requests with the GET method -// Will return the struct specified in Generics -func Get[T any](ctx context.Context, cfg *config.Config, url string, opts ...Option) (T, error) { - return make[T](ctx, cfg, url, http.MethodGet, nil, opts...) -} - -// Post makes requests with the POST method -// Will return the struct specified in Generics -func Post[T any](ctx context.Context, cfg *config.Config, url string, body any, opts ...Option) (T, error) { - return make[T](ctx, cfg, url, http.MethodPost, body, opts...) -} - -// Put makes requests with the PUT method -// Will return the struct specified in Generics -func Put[T any](ctx context.Context, cfg *config.Config, url string, body any, opts ...Option) (T, error) { - return make[T](ctx, cfg, url, http.MethodPut, body, opts...) -} - -// Patch makes requests with the PATCH method -// Will return the struct specified in Generics -func Patch[T any](ctx context.Context, cfg *config.Config, url string, body any, opts ...Option) (T, error) { - return make[T](ctx, cfg, url, http.MethodPatch, body, opts...) -} - -// Delete makes requests with the DELETE method -// Will return the struct specified in Generics -func Delete[T any](ctx context.Context, cfg *config.Config, url string, body any, opts ...Option) (T, error) { - return make[T](ctx, cfg, url, http.MethodDelete, body, opts...) -} - -func make[T any](ctx context.Context, cfg *config.Config, url, method string, body any, opts ...Option) (T, error) { - var result T - - req, err := makeRequest(ctx, cfg, method, url, body, opts...) - if err != nil { - return result, err - } - - b, err := httpclient.Send(cfg.Requester, req) - if err != nil { - return result, err - } - - return makeResponse(b, result) -} - -func makeRequest(ctx context.Context, cfg *config.Config, method, url string, body any, opts ...Option) (*http.Request, error) { - req, err := makeHTTPRequest(ctx, method, url, body) - if err != nil { - return nil, fmt.Errorf("error creating request: %w", err) - } - - // Apply all the functional options to configure the baseclient. - opt := &clientOption{} - for _, o := range opts { - o(opt) - } - - makeHeaders(req, cfg) - makeQueryParams(req, opt.queryParams) - - if err = makePathParams(req, opt.pathParams); err != nil { - return nil, err - } - - return req, nil -} - -func makeHTTPRequest(ctx context.Context, method, url string, body any) (*http.Request, error) { - b, err := makeBody(body) - if err != nil { - return nil, err - } - - return http.NewRequestWithContext(ctx, method, url, b) -} - -func makeHeaders(req *http.Request, cfg *config.Config) { - req.Header.Set("X-Product-Id", productID) - req.Header.Set("Accept", "application/json") - req.Header.Set("Content-Type", "application/json; charset=UTF-8") - req.Header.Set("User-Agent", userAgent) - req.Header.Set("X-Tracking-Id", trackingID) - req.Header.Set("Authorization", "Bearer "+cfg.AccessToken) - req.Header.Set("X-Idempotency-Key", uuid.New().String()) - req.Header.Set("X-Request-Id", uuid.New().String()) - - if cfg.CorporationID != "" { - req.Header.Set("X-Corporation-Id", cfg.CorporationID) - } - if cfg.IntegratorID != "" { - req.Header.Set("X-Integrator-Id", cfg.IntegratorID) - } - if cfg.PlatformID != "" { - req.Header.Set("X-Platform-Id", cfg.PlatformID) - } -} - -func makeBody(body any) (io.Reader, error) { - if body == nil { - return nil, nil - } - - b, err := json.Marshal(&body) - if err != nil { - return nil, fmt.Errorf("error marshaling request body: %w", err) - } - - return strings.NewReader(string(b)), nil -} - -func makePathParams(req *http.Request, params map[string]string) error { - pathURL := req.URL.Path - - for k, v := range params { - pathParam := ":" + k - pathURL = strings.Replace(pathURL, pathParam, v, 1) - } - - if err := validatePathParams(pathURL); err != nil { - return err - } - - req.URL.Path = pathURL - - return nil -} - -func makeQueryParams(req *http.Request, params map[string]string) { - queryParams := url.Values{} - - if len(params) == 0 { - return - } - - for k, v := range params { - queryParams.Add(k, v) - } - - req.URL.RawQuery = queryParams.Encode() -} - -func makeResponse[T any](b []byte, response T) (T, error) { - if err := json.Unmarshal(b, &response); err != nil { - return response, err - } - - return response, nil -} - -func validatePathParams(pathURL string) error { - if strings.Contains(pathURL, ":") { - words := strings.Split(pathURL, "/") - var paramsNotReplaced []string - for _, word := range words { - if strings.Contains(word, ":") { - paramsNotReplaced = append(paramsNotReplaced, strings.Replace(word, ":", "", 1)) - } - } - return fmt.Errorf("path parameters not informed: %s", strings.Join(paramsNotReplaced, ",")) - } - - return nil -} diff --git a/pkg/internal/baseclient/client_option.go b/pkg/internal/baseclient/client_option.go deleted file mode 100644 index 8d8d93dc..00000000 --- a/pkg/internal/baseclient/client_option.go +++ /dev/null @@ -1,27 +0,0 @@ -package baseclient - -// ClientOption allows sending options in the http baseclient -type clientOption struct { - pathParams map[string]string - queryParams map[string]string -} - -type Option func(*clientOption) - -// WithPathParams allows sending path parameters in the request. -func WithPathParams(params map[string]string) Option { - return func(c *clientOption) { - if params != nil { - c.pathParams = params - } - } -} - -// WithQueryParams allows sending query parameters in the request. -func WithQueryParams(params map[string]string) Option { - return func(c *clientOption) { - if params != nil { - c.queryParams = params - } - } -} diff --git a/pkg/internal/baseclient/client_test.go b/pkg/internal/baseclient/client_test.go deleted file mode 100644 index 921e86d7..00000000 --- a/pkg/internal/baseclient/client_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package baseclient - -import ( - "context" - "net/http" - "net/url" - "testing" - - "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/requester" - "github.com/stretchr/testify/assert" -) - -func TestMakePathParams(t *testing.T) { - type args struct { - url string - params map[string]string - } - tests := []struct { - name string - args args - wantURL string - wantMsgErr string - }{ - { - name: "should_replace_one_path_param", - args: args{ - url: "http://localhost/payments/:payment_id", - params: map[string]string{ - "payment_id": "1234567890", - }, - }, - wantURL: "http://localhost/payments/1234567890", - }, - { - name: "should_return_path_param_not_informed", - args: args{ - url: "http://localhost/customers/:customer_id", - params: map[string]string{ - "payment_id": "1234567890", - }, - }, - wantMsgErr: "path parameters not informed: customer_id", - }, - { - name: "should_return_two_path_params_not_informed", - args: args{ - url: "http://localhost/tests/:test_id/units/:unit_id", - params: map[string]string{ - "integrate_id": "1234567890", - }, - }, - wantMsgErr: "path parameters not informed: test_id,unit_id", - }, - { - name: "should_return_the_same_path_url", - args: args{ - url: "http://localhost/tests/", - params: map[string]string{ - "integrate_id": "1234567890", - }, - }, - wantURL: "http://localhost/tests/", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req, _ := http.NewRequest(http.MethodGet, tt.args.url, nil) - - err := makePathParams(req, tt.args.params) - if err != nil && err.Error() != tt.wantMsgErr { - t.Errorf("makeParams() msgError = %v, wantMsgErr %v", err.Error(), tt.wantMsgErr) - return - } - - if err == nil && tt.wantURL != req.URL.String() { - t.Errorf("makeParams() wantURL = %v, gotURL %v", tt.wantURL, req.URL.String()) - } - }) - } -} - -func TestMakeQueryParams(t *testing.T) { - type args struct { - url string - params map[string]string - } - tests := []struct { - name string - args args - wantURL string - }{ - { - name: "should_add_one_query_param", - args: args{ - url: "http://localhost/payments/1234567890/search", - params: map[string]string{ - "external_resource": "as2f12345", - }, - }, - wantURL: "http://localhost/payments/1234567890/search?external_resource=as2f12345", - }, - { - name: "should_add_two_query_params", - args: args{ - url: "http://localhost/payments/1234567890/search", - params: map[string]string{ - "external_resource": "as2f12345", - "offset": "2", - }, - }, - wantURL: "http://localhost/payments/1234567890/search?external_resource=as2f12345&offset=2", - }, - { - name: "should_return_the_same_path_url", - args: args{ - url: "http://localhost/tests/", - params: map[string]string{}, - }, - wantURL: "http://localhost/tests/", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req, _ := http.NewRequest(http.MethodGet, tt.args.url, nil) - - makeQueryParams(req, tt.args.params) - if tt.wantURL != req.URL.String() { - t.Errorf("makeQueryParams() wantURL = %v, gotURL %v", tt.wantURL, req.URL.String()) - } - }) - } -} - -func Test_makeRequest(t *testing.T) { - type args struct { - cfg *config.Config - method string - url string - body any - opts []Option - } - tests := []struct { - name string - args args - want *http.Request - wantErr bool - }{ - { - name: "should_create_http_request_success", - args: args{ - cfg: &config.Config{ - AccessToken: "", - Requester: requester.Default(), - }, - method: http.MethodGet, - url: "https://test.com/tests/:id", - body: nil, - opts: []Option{ - WithPathParams(map[string]string{ - "id": "123", - }), - }, - }, - want: &http.Request{ - Method: http.MethodGet, - URL: &url.URL{ - Scheme: "https", - Host: "test.com", - Path: "/tests/123", - }, - Host: "test.com", - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() - got, err := makeRequest(ctx, tt.args.cfg, tt.args.method, tt.args.url, tt.args.body, tt.args.opts...) - if (err != nil) != tt.wantErr { - t.Errorf("makeRequest() error = %v, wantErr %v", err, tt.wantErr) - return - } - - assert.Equal(t, tt.want.URL.String(), got.URL.String()) - assert.NotEmpty(t, got.Header.Get("X-Idempotency-Key")) - assert.NotEmpty(t, got.Header.Get("X-Request-Id")) - }) - } -} diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go new file mode 100644 index 00000000..ab34dcc6 --- /dev/null +++ b/pkg/internal/httpclient/helper.go @@ -0,0 +1,160 @@ +package httpclient + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "runtime" + "strings" + + "github.com/google/uuid" + "github.com/mercadopago/sdk-go/pkg/config" +) + +const ( + currentSDKVersion string = "x.x.x" + productID string = "abc" +) + +var ( + pathParamFormat = regexp.MustCompile("[{}]") + + userAgent = fmt.Sprintf("MercadoPago Go SDK/%s", currentSDKVersion) + trackingID = fmt.Sprintf("platform:%s,type:SDK%s,so;", runtime.Version(), currentSDKVersion) +) + +type CallData struct { + Body any + PathParams map[string]string + QueryParams map[string]string + + Method string + URL string +} + +func Run[T any](ctx context.Context, cfg *config.Config, callData CallData) (T, error) { + var result T + + req, err := createRequest(ctx, cfg, callData) + if err != nil { + return result, err + } + + b, err := Send(cfg.Requester, req) + if err != nil { + return result, err + } + + return wrapUnmarshal(b, result) +} + +func createRequest(ctx context.Context, cfg *config.Config, callData CallData) (*http.Request, error) { + body, err := wrapMarshal(callData.Body) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, callData.Method, callData.URL, body) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + + setHeaders(req, cfg) + if err = setPathParams(req, callData.QueryParams); err != nil { + return nil, err + } + setQueryParams(req, callData.QueryParams) + + return req, nil +} + +func wrapMarshal(body any) (io.Reader, error) { + if body == nil { + return nil, nil + } + + b, err := json.Marshal(&body) + if err != nil { + return nil, fmt.Errorf("error marshaling request body: %w", err) + } + + return strings.NewReader(string(b)), nil +} + +func setHeaders(req *http.Request, cfg *config.Config) { + req.Header.Set("X-Product-Id", productID) + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/json; charset=UTF-8") + req.Header.Set("User-Agent", userAgent) + req.Header.Set("X-Tracking-Id", trackingID) + req.Header.Set("Authorization", "Bearer "+cfg.AccessToken) + req.Header.Set("X-Idempotency-Key", uuid.New().String()) + req.Header.Set("X-Request-Id", uuid.New().String()) + + if cfg.CorporationID != "" { + req.Header.Set("X-Corporation-Id", cfg.CorporationID) + } + if cfg.IntegratorID != "" { + req.Header.Set("X-Integrator-Id", cfg.IntegratorID) + } + if cfg.PlatformID != "" { + req.Header.Set("X-Platform-Id", cfg.PlatformID) + } +} + +func setQueryParams(req *http.Request, params map[string]string) { + if len(params) == 0 { + return + } + + queryParams := url.Values{} + for k, v := range params { + queryParams.Add(k, v) + } + req.URL.RawQuery = queryParams.Encode() +} + +func setPathParams(req *http.Request, params map[string]string) error { + pathURL := req.URL.Path + + for k, v := range params { + pathParam := fmt.Sprintf("{%s}", k) + pathURL = strings.Replace(pathURL, pathParam, v, 1) + } + + if err := checkReplaces(pathURL); err != nil { + return err + } + + req.URL.Path = pathURL + return nil +} + +func checkReplaces(pathURL string) error { + if pathParamFormat.MatchString(pathURL) { + elements := strings.Split(pathURL, "/") + + notReplaced := []string{} + for _, e := range elements { + if pathParamFormat.MatchString(e) { + notReplaced = append(notReplaced, e) + } + } + + return fmt.Errorf("path parameters not informed: %s", strings.Join(notReplaced, ",")) + } + + return nil +} + +func wrapUnmarshal[T any](b []byte, response T) (T, error) { + if err := json.Unmarshal(b, &response); err != nil { + return response, err + } + + return response, nil +} From 0eb39617a462eb5bff6a450bc8d870249ba3169f Mon Sep 17 00:00:00 2001 From: gabs Date: Fri, 1 Mar 2024 16:14:20 -0300 Subject: [PATCH 02/19] Refactor clients to use the new way to call apis --- examples/apis/customer/search/main.go | 4 +- examples/apis/refund/partial_refund/main.go | 2 +- go.mod | 11 +-- go.sum | 10 --- pkg/cardtoken/client.go | 10 ++- pkg/customer/client.go | 48 ++++++++---- pkg/customer/client_test.go | 11 --- pkg/customer/search_request.go | 30 ++++---- pkg/customercard/client.go | 54 +++++++++---- pkg/identificationtype/client.go | 9 ++- pkg/internal/httpclient/helper.go | 26 +++---- pkg/merchantorder/client.go | 46 ++++++----- pkg/merchantorder/search_request.go | 30 ++++---- pkg/oauth/client.go | 17 ++++- pkg/payment/client.go | 84 +++++++++++++++------ pkg/payment/search_request.go | 30 ++++---- pkg/paymentmethod/client.go | 9 ++- pkg/point/client.go | 47 +++++++++--- pkg/preference/client.go | 44 +++++++---- pkg/preference/search_request.go | 27 +++---- pkg/refund/client.go | 58 ++++++++++---- pkg/refund/client_test.go | 2 +- pkg/user/client.go | 9 ++- test/integration/refund/refund_test.go | 4 +- 24 files changed, 389 insertions(+), 233 deletions(-) diff --git a/examples/apis/customer/search/main.go b/examples/apis/customer/search/main.go index 999a3c3e..c026ca35 100644 --- a/examples/apis/customer/search/main.go +++ b/examples/apis/customer/search/main.go @@ -9,7 +9,7 @@ import ( ) func main() { - accessToken := "{{ACCESS_TOKEN}}" + accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" cfg, err := config.New(accessToken) if err != nil { @@ -19,7 +19,7 @@ func main() { req := customer.SearchRequest{ Filters: map[string]string{ - "email": "{{EMAIL}}", + "EMAIL": "akdsokdoakdoasakdoas@testuser.com", }, } diff --git a/examples/apis/refund/partial_refund/main.go b/examples/apis/refund/partial_refund/main.go index c493be8a..1dcb64fd 100644 --- a/examples/apis/refund/partial_refund/main.go +++ b/examples/apis/refund/partial_refund/main.go @@ -40,7 +40,7 @@ func main() { partialAmount := pay.TransactionAmount - 10.0 refundClient := refund.NewClient(cfg) - ref, err := refundClient.CreatePartialRefund(context.Background(), partialAmount, pay.ID) + ref, err := refundClient.CreatePartialRefund(context.Background(), pay.ID, partialAmount) if err != nil { fmt.Println(err) return diff --git a/go.mod b/go.mod index 1b9c281b..83d08ca2 100644 --- a/go.mod +++ b/go.mod @@ -2,13 +2,4 @@ module github.com/mercadopago/sdk-go go 1.21.0 -require ( - github.com/google/uuid v1.5.0 - github.com/stretchr/testify v1.8.4 -) - -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) +require github.com/google/uuid v1.5.0 diff --git a/go.sum b/go.sum index 53bfb8c3..040e2213 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,2 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/cardtoken/client.go b/pkg/cardtoken/client.go index 59c22956..55a9783e 100644 --- a/pkg/cardtoken/client.go +++ b/pkg/cardtoken/client.go @@ -2,9 +2,10 @@ package cardtoken import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const url = "https://api.mercadopago.com/v1/card_tokens" @@ -25,7 +26,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, url, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: url, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/customer/client.go b/pkg/customer/client.go index fccd5a7c..5071bb03 100644 --- a/pkg/customer/client.go +++ b/pkg/customer/client.go @@ -2,17 +2,16 @@ package customer import ( "context" - "fmt" - "net/url" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( urlBase = "https://api.mercadopago.com/v1/customers" urlSearch = urlBase + "/search" - urlWithID = urlBase + "/:id" + urlWithID = urlBase + "/{id}" ) // Client contains the methods to interact with the Customers API. @@ -21,14 +20,17 @@ type Client interface { // It is a post request to the endpoint: https://api.mercadopago.com/v1/customers // Reference: https://www.mercadopago.com/developers/en/reference/customers/_customers/post/ Create(ctx context.Context, request Request) (*Response, error) + // Search find all customer information using specific filters. // It is a get request to the endpoint: https://api.mercadopago.com/v1/customers/search // Reference: https://www.mercadopago.com/developers/en/reference/customers/_customers_search/get/ Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) + // Get check all the information of a client created with the client ID of your choice. // It is a get request to the endpoint: https://api.mercadopago.com/v1/customers/{id} // Reference: https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/ Get(ctx context.Context, id string) (*Response, error) + // Update renew the data of a customer. // It is a put request to the endpoint: https://api.mercadopago.com/v1/customers // Reference: https://www.mercadopago.com/developers/en/reference/customers/_customers_id/put/ @@ -48,7 +50,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -57,15 +64,14 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - params := request.Parameters() + request.Check() - parsedURL, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing url: %w", err) + callData := httpclient.CallData{ + QueryParams: request.Filters, + Method: http.MethodGet, + URL: urlSearch, } - parsedURL.RawQuery = params - - result, err := baseclient.Get[*SearchResponse](ctx, c.cfg, parsedURL.String()) + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -74,11 +80,16 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp } func (c *client) Get(ctx context.Context, id string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "id": id, } - result, err := baseclient.Get[*Response](ctx, c.cfg, urlWithID, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -87,11 +98,16 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { } func (c *client) Update(ctx context.Context, id string, request Request) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "id": id, } - result, err := baseclient.Put[*Response](ctx, c.cfg, urlWithID, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/customer/client_test.go b/pkg/customer/client_test.go index d7f3f085..245f6a42 100644 --- a/pkg/customer/client_test.go +++ b/pkg/customer/client_test.go @@ -117,17 +117,6 @@ func TestSearch(t *testing.T) { want *SearchResponse wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_return_response", fields: fields{ diff --git a/pkg/customer/search_request.go b/pkg/customer/search_request.go index e16fa0c3..87b168a3 100644 --- a/pkg/customer/search_request.go +++ b/pkg/customer/search_request.go @@ -1,25 +1,26 @@ package customer -import ( - "net/url" -) +import "strings" // SearchRequest is the request to search services. // Filters field can receive a lot of parameters. For details, see: // https://www.mercadopago.com/developers/en/reference/customers/_customers_search/get. type SearchRequest struct { + Filters map[string]string + Limit string Offset string - - Filters map[string]string } -// Parameters transforms SearchRequest into url params. -func (s SearchRequest) Parameters() string { - params := url.Values{} - - for k, v := range s.Filters { - params.Add(k, v) +// Check sets values for limit and offset when not sent. +func (s *SearchRequest) Check() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -27,16 +28,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } diff --git a/pkg/customercard/client.go b/pkg/customercard/client.go index c9f5a8b1..1d27c20a 100644 --- a/pkg/customercard/client.go +++ b/pkg/customercard/client.go @@ -2,14 +2,15 @@ package customercard import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( - urlBase = "https://api.mercadopago.com/v1/customers/:customer_id/cards" - urlWithID = urlBase + "/:card_id" + urlBase = "https://api.mercadopago.com/v1/customers/{customer_id}/cards" + urlWithID = urlBase + "/{card_id}" ) // Client contains the methods to interact with the Customer Cards API. @@ -53,11 +54,17 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, customerID string, request Request) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "customer_id": customerID, } - result, err := baseclient.Post[*Response](ctx, c.config, urlBase, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.config, callData) if err != nil { return nil, err } @@ -66,12 +73,17 @@ func (c *client) Create(ctx context.Context, customerID string, request Request) } func (c *client) Get(ctx context.Context, customerID, cardID string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "customer_id": customerID, "card_id": cardID, } - result, err := baseclient.Get[*Response](ctx, c.config, urlWithID, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.config, callData) if err != nil { return nil, err } @@ -80,12 +92,18 @@ func (c *client) Get(ctx context.Context, customerID, cardID string) (*Response, } func (c *client) Update(ctx context.Context, customerID, cardID string, request Request) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "customer_id": customerID, "card_id": cardID, } - result, err := baseclient.Put[*Response](ctx, c.config, urlWithID, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.config, callData) if err != nil { return nil, err } @@ -94,12 +112,17 @@ func (c *client) Update(ctx context.Context, customerID, cardID string, request } func (c *client) Delete(ctx context.Context, customerID, cardID string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "customer_id": customerID, "card_id": cardID, } - result, err := baseclient.Delete[*Response](ctx, c.config, urlWithID, nil, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodDelete, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.config, callData) if err != nil { return nil, err } @@ -108,11 +131,16 @@ func (c *client) Delete(ctx context.Context, customerID, cardID string) (*Respon } func (c *client) List(ctx context.Context, customerID string) ([]Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "customer_id": customerID, } - result, err := baseclient.Get[[]Response](ctx, c.config, urlBase, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlBase, + } + result, err := httpclient.Run[[]Response](ctx, c.config, callData) if err != nil { return nil, err } diff --git a/pkg/identificationtype/client.go b/pkg/identificationtype/client.go index a21514a9..ad5cae1d 100644 --- a/pkg/identificationtype/client.go +++ b/pkg/identificationtype/client.go @@ -2,9 +2,10 @@ package identificationtype import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const url = "https://api.mercadopago.com/v1/identification_types" @@ -28,7 +29,11 @@ func NewClient(cfg *config.Config) Client { } func (c *client) List(ctx context.Context) ([]Response, error) { - result, err := baseclient.Get[[]Response](ctx, c.cfg, url) + callData := httpclient.CallData{ + Method: http.MethodGet, + URL: url, + } + result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go index ab34dcc6..135c3ad0 100644 --- a/pkg/internal/httpclient/helper.go +++ b/pkg/internal/httpclient/helper.go @@ -64,7 +64,7 @@ func createRequest(ctx context.Context, cfg *config.Config, callData CallData) ( } setHeaders(req, cfg) - if err = setPathParams(req, callData.QueryParams); err != nil { + if err = setPathParams(req, callData.PathParams); err != nil { return nil, err } setQueryParams(req, callData.QueryParams) @@ -106,18 +106,6 @@ func setHeaders(req *http.Request, cfg *config.Config) { } } -func setQueryParams(req *http.Request, params map[string]string) { - if len(params) == 0 { - return - } - - queryParams := url.Values{} - for k, v := range params { - queryParams.Add(k, v) - } - req.URL.RawQuery = queryParams.Encode() -} - func setPathParams(req *http.Request, params map[string]string) error { pathURL := req.URL.Path @@ -151,6 +139,18 @@ func checkReplaces(pathURL string) error { return nil } +func setQueryParams(req *http.Request, params map[string]string) { + if len(params) == 0 { + return + } + + queryParams := url.Values{} + for k, v := range params { + queryParams.Add(k, v) + } + req.URL.RawQuery = queryParams.Encode() +} + func wrapUnmarshal[T any](b []byte, response T) (T, error) { if err := json.Unmarshal(b, &response); err != nil { return response, err diff --git a/pkg/merchantorder/client.go b/pkg/merchantorder/client.go index 8f6175d4..88ebff35 100644 --- a/pkg/merchantorder/client.go +++ b/pkg/merchantorder/client.go @@ -2,12 +2,11 @@ package merchantorder import ( "context" - "fmt" - "net/url" + "net/http" "strconv" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -52,11 +51,16 @@ func NewClient(c *config.Config) Client { } func (c *client) Get(ctx context.Context, id int64) (*Response, error) { - param := map[string]string{ + pathParams := map[string]string{ "id": strconv.Itoa(int(id)), } - result, err := baseclient.Get[*Response](ctx, c.cfg, urlWithID, baseclient.WithPathParams(param)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -65,17 +69,14 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - params := request.Parameters() + request.Check() - url, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing url: %w", err) + callData := httpclient.CallData{ + QueryParams: request.Filters, + Method: http.MethodGet, + URL: urlSearch, } - - url.RawQuery = params - - result, err := baseclient.Get[*SearchResponse](ctx, c.cfg, url.String()) - + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -84,11 +85,17 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp } func (c *client) Update(ctx context.Context, request UpdateRequest, id int64) (*Response, error) { - param := map[string]string{ + pathParams := map[string]string{ "id": strconv.Itoa(int(id)), } - result, err := baseclient.Put[*Response](ctx, c.cfg, urlWithID, request, baseclient.WithPathParams(param)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -97,7 +104,12 @@ func (c *client) Update(ctx context.Context, request UpdateRequest, id int64) (* } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/merchantorder/search_request.go b/pkg/merchantorder/search_request.go index 7fc24ab0..a2c7ec1e 100644 --- a/pkg/merchantorder/search_request.go +++ b/pkg/merchantorder/search_request.go @@ -1,25 +1,26 @@ package merchantorder -import ( - "net/url" -) +import "strings" // SearchRequest is the request to search services. // Filters field can receive a lot of paramaters. For details, see: // https://www.mercadopago.com/developers/en/reference/merchant_orders/_merchant_orders_search/get. type SearchRequest struct { + Filters map[string]string + Limit string Offset string - - Filters map[string]string } -// Parameters transforms SearchRequest into url params. -func (s SearchRequest) Parameters() string { - params := url.Values{} - - for k, v := range s.Filters { - params.Add(k, v) +// Check sets values for limit and offset when not sent. +func (s *SearchRequest) Check() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -27,16 +28,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } diff --git a/pkg/oauth/client.go b/pkg/oauth/client.go index 7b9cb53a..b11f288e 100644 --- a/pkg/oauth/client.go +++ b/pkg/oauth/client.go @@ -2,10 +2,11 @@ package oauth import ( "context" + "net/http" "net/url" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -50,7 +51,12 @@ func (c *client) Create(ctx context.Context, authorizationCode, redirectURI stri GrantType: "authorization_code", } - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -89,7 +95,12 @@ func (c *client) Refresh(ctx context.Context, refreshToken string) (*Response, e GrantType: "refresh_token", } - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/payment/client.go b/pkg/payment/client.go index 6d4d0456..8b6a7d7b 100644 --- a/pkg/payment/client.go +++ b/pkg/payment/client.go @@ -2,13 +2,11 @@ package payment import ( "context" - "fmt" - "net/url" + "net/http" "strconv" - "strings" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -60,7 +58,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -68,16 +71,15 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) return result, nil } -func (c *client) Search(ctx context.Context, dto SearchRequest) (*SearchResponse, error) { - params := dto.Parameters() +func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { + request.Check() - url, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing url: %w", err) + callData := httpclient.CallData{ + QueryParams: request.Filters, + Method: http.MethodGet, + URL: urlSearch, } - url.RawQuery = params - - result, err := baseclient.Get[*SearchResponse](ctx, c.cfg, url.String()) + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -86,9 +88,16 @@ func (c *client) Search(ctx context.Context, dto SearchRequest) (*SearchResponse } func (c *client) Get(ctx context.Context, id int64) (*Response, error) { - conv := strconv.Itoa(int(id)) + pathParams := map[string]string{ + "id": strconv.Itoa(int(id)), + } - result, err := baseclient.Get[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", conv, 1)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -97,10 +106,19 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { } func (c *client) Cancel(ctx context.Context, id int64) (*Response, error) { - dto := &CancelRequest{Status: "cancelled"} - conv := strconv.Itoa(int(id)) + request := &CancelRequest{Status: "cancelled"} + + pathParams := map[string]string{ + "id": strconv.Itoa(int(id)), + } - result, err := baseclient.Put[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", conv, 1), dto) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -109,10 +127,19 @@ func (c *client) Cancel(ctx context.Context, id int64) (*Response, error) { } func (c *client) Capture(ctx context.Context, id int64) (*Response, error) { - dto := &CaptureRequest{Capture: true} - conv := strconv.Itoa(int(id)) + request := &CaptureRequest{Capture: true} + + pathParams := map[string]string{ + "id": strconv.Itoa(int(id)), + } - result, err := baseclient.Put[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", conv, 1), dto) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -121,10 +148,19 @@ func (c *client) Capture(ctx context.Context, id int64) (*Response, error) { } func (c *client) CaptureAmount(ctx context.Context, id int64, amount float64) (*Response, error) { - dto := &CaptureRequest{TransactionAmount: amount, Capture: true} - conv := strconv.Itoa(int(id)) + request := &CaptureRequest{TransactionAmount: amount, Capture: true} - result, err := baseclient.Put[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", conv, 1), dto) + pathParams := map[string]string{ + "id": strconv.Itoa(int(id)), + } + + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/payment/search_request.go b/pkg/payment/search_request.go index 9d8d5801..5f09d8c7 100644 --- a/pkg/payment/search_request.go +++ b/pkg/payment/search_request.go @@ -1,25 +1,26 @@ package payment -import ( - "net/url" -) +import "strings" // SearchRequest is the request to search services. // Filters field can receive a lot of paramaters. For details, see: // https://www.mercadopago.com.br/developers/pt/reference/payments/_payments_search/get. type SearchRequest struct { + Filters map[string]string + Limit string Offset string - - Filters map[string]string } -// Parameters transforms SearchRequest into url params. -func (s SearchRequest) Parameters() string { - params := url.Values{} - - for k, v := range s.Filters { - params.Add(k, v) +// Check sets values for limit and offset when not sent. +func (s *SearchRequest) Check() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -27,16 +28,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } diff --git a/pkg/paymentmethod/client.go b/pkg/paymentmethod/client.go index a35fd9d4..769bb9d8 100644 --- a/pkg/paymentmethod/client.go +++ b/pkg/paymentmethod/client.go @@ -2,9 +2,10 @@ package paymentmethod import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const url = "https://api.mercadopago.com/v1/payment_methods" @@ -28,7 +29,11 @@ func NewClient(cfg *config.Config) Client { } func (c *client) List(ctx context.Context) ([]Response, error) { - result, err := baseclient.Get[[]Response](ctx, c.cfg, url) + callData := httpclient.CallData{ + Method: http.MethodGet, + URL: url, + } + result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/point/client.go b/pkg/point/client.go index 9ebdcfd5..5a3ef4fa 100644 --- a/pkg/point/client.go +++ b/pkg/point/client.go @@ -2,9 +2,10 @@ package point import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -56,11 +57,17 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, deviceID string, request CreateRequest) (*CreateResponse, error) { - params := map[string]string{ + pathParams := map[string]string{ "device_id": deviceID, } - result, err := baseclient.Post[*CreateResponse](ctx, c.cfg, urlPaymentIntent, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPost, + URL: urlPaymentIntent, + } + result, err := httpclient.Run[*CreateResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -69,11 +76,16 @@ func (c *client) Create(ctx context.Context, deviceID string, request CreateRequ } func (c *client) Get(ctx context.Context, paymentIntentID string) (*GetResponse, error) { - params := map[string]string{ + pathParams := map[string]string{ "payment_intent_id": paymentIntentID, } - result, err := baseclient.Get[*GetResponse](ctx, c.cfg, urlPaymentIntentGet, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlPaymentIntentGet, + } + result, err := httpclient.Run[*GetResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -82,12 +94,17 @@ func (c *client) Get(ctx context.Context, paymentIntentID string) (*GetResponse, } func (c *client) Cancel(ctx context.Context, deviceID string, paymentIntentID string) (*CancelResponse, error) { - params := map[string]string{ + pathParams := map[string]string{ "device_id": deviceID, "payment_intent_id": paymentIntentID, } - result, err := baseclient.Delete[*CancelResponse](ctx, c.cfg, urlPaymentIntentCancel, nil, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodDelete, + URL: urlPaymentIntentCancel, + } + result, err := httpclient.Run[*CancelResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -96,7 +113,11 @@ func (c *client) Cancel(ctx context.Context, deviceID string, paymentIntentID st } func (c *client) ListDevices(ctx context.Context) (*DevicesResponse, error) { - result, err := baseclient.Get[*DevicesResponse](ctx, c.cfg, urlDevices) + callData := httpclient.CallData{ + Method: http.MethodGet, + URL: urlDevices, + } + result, err := httpclient.Run[*DevicesResponse](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -105,11 +126,17 @@ func (c *client) ListDevices(ctx context.Context) (*DevicesResponse, error) { } func (c *client) UpdateDeviceOperatingMode(ctx context.Context, deviceID string, request UpdateDeviceOperatingModeRequest) (*OperationModeResponse, error) { - params := map[string]string{ + pathParams := map[string]string{ "device_id": deviceID, } - result, err := baseclient.Patch[*OperationModeResponse](ctx, c.cfg, urlDevicesWithID, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPatch, + URL: urlDevicesWithID, + } + result, err := httpclient.Run[*OperationModeResponse](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/preference/client.go b/pkg/preference/client.go index 16bbc645..ad8d1687 100644 --- a/pkg/preference/client.go +++ b/pkg/preference/client.go @@ -2,11 +2,10 @@ package preference import ( "context" - "fmt" - "net/url" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -51,7 +50,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -60,11 +64,16 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) } func (c *client) Get(ctx context.Context, id string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "id": id, } - result, err := baseclient.Get[*Response](ctx, c.cfg, urlWithID, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -73,11 +82,17 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { } func (c *client) Update(ctx context.Context, request Request, id string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "id": id, } - result, err := baseclient.Put[*Response](ctx, c.cfg, urlWithID, request, baseclient.WithPathParams(params)) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -86,15 +101,14 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponsePage, error) { - params := request.Parameters() + request.Check() - url, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing url: %w", err) + callData := httpclient.CallData{ + Body: request, + Method: http.MethodGet, + URL: urlBase, } - url.RawQuery = params - - result, err := baseclient.Get[*SearchResponsePage](ctx, c.cfg, url.String()) + result, err := httpclient.Run[*SearchResponsePage](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/preference/search_request.go b/pkg/preference/search_request.go index 0c0f6167..bb5da31f 100644 --- a/pkg/preference/search_request.go +++ b/pkg/preference/search_request.go @@ -1,19 +1,23 @@ package preference -import "net/url" +import "strings" // SearchRequest contains filters accepted in search type SearchRequest struct { - Limit string - Offset string Filters map[string]string -} -func (s SearchRequest) Parameters() string { - params := url.Values{} + Limit string + Offset string +} - for k, v := range s.Filters { - params.Add(k, v) +func (s *SearchRequest) Check() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -21,16 +25,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } diff --git a/pkg/refund/client.go b/pkg/refund/client.go index 55575cb5..797d40a9 100644 --- a/pkg/refund/client.go +++ b/pkg/refund/client.go @@ -2,11 +2,11 @@ package refund import ( "context" + "net/http" "strconv" - "strings" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -34,7 +34,7 @@ type Client interface { // CreatePartialRefund create a partial refund by payment id. // It is a post request to the endpoint: https://api.mercadopago.com/v1/payments/{id}/refunds // Reference: https://www.mercadopago.com/developers/en/reference/chargebacks/_payments_id_refunds/post - CreatePartialRefund(ctx context.Context, amount float64, paymentID int64) (*Response, error) + CreatePartialRefund(ctx context.Context, paymentID int64, amount float64) (*Response, error) } // client is the implementation of Client. @@ -50,12 +50,17 @@ func NewClient(c *config.Config) Client { } func (c *client) Get(ctx context.Context, paymentID, refundID int64) (*Response, error) { - convertedPaymentID := strconv.Itoa(int(paymentID)) - convertedRefundID := strconv.Itoa(int(refundID)) - - url := strings.NewReplacer("{id}", convertedPaymentID, "{refund_id}", convertedRefundID).Replace(urlWithID) + pathParams := map[string]string{ + "id": strconv.Itoa(int(paymentID)), + "refund_id": strconv.Itoa(int(refundID)), + } - result, err := baseclient.Get[*Response](ctx, c.cfg, url) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -64,9 +69,16 @@ func (c *client) Get(ctx context.Context, paymentID, refundID int64) (*Response, } func (c *client) List(ctx context.Context, paymentID int64) ([]Response, error) { - convertedRefundID := strconv.Itoa(int(paymentID)) + pathParams := map[string]string{ + "id": strconv.Itoa(int(paymentID)), + } - result, err := baseclient.Get[[]Response](ctx, c.cfg, strings.Replace(urlBase, "{id}", convertedRefundID, 1)) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlBase, + } + result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -75,9 +87,16 @@ func (c *client) List(ctx context.Context, paymentID int64) ([]Response, error) } func (c *client) Create(ctx context.Context, paymentID int64) (*Response, error) { - convertedPaymentID := strconv.Itoa(int(paymentID)) + pathParams := map[string]string{ + "id": strconv.Itoa(int(paymentID)), + } - result, err := baseclient.Post[*Response](ctx, c.cfg, strings.Replace(urlBase, "{id}", convertedPaymentID, 1), nil) + callData := httpclient.CallData{ + PathParams: pathParams, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } @@ -85,12 +104,19 @@ func (c *client) Create(ctx context.Context, paymentID int64) (*Response, error) return result, nil } -func (c *client) CreatePartialRefund(ctx context.Context, amount float64, paymentID int64) (*Response, error) { +func (c *client) CreatePartialRefund(ctx context.Context, paymentID int64, amount float64) (*Response, error) { request := &Request{Amount: amount} + pathParams := map[string]string{ + "id": strconv.Itoa(int(paymentID)), + } - convertedPaymentID := strconv.Itoa(int(paymentID)) - - result, err := baseclient.Post[*Response](ctx, c.cfg, strings.Replace(urlBase, "{id}", convertedPaymentID, 1), request) + callData := httpclient.CallData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/pkg/refund/client_test.go b/pkg/refund/client_test.go index fd4be219..d2d54fdc 100644 --- a/pkg/refund/client_test.go +++ b/pkg/refund/client_test.go @@ -220,7 +220,7 @@ func TestCreatePartialRefund(t *testing.T) { c := &client{ cfg: tt.fields.config, } - got, err := c.CreatePartialRefund(tt.args.ctx, tt.args.amount, 1622029222) + got, err := c.CreatePartialRefund(tt.args.ctx, 1622029222, tt.args.amount) gotErr := "" if err != nil { gotErr = err.Error() diff --git a/pkg/user/client.go b/pkg/user/client.go index 8960d0c7..dc02d9a8 100644 --- a/pkg/user/client.go +++ b/pkg/user/client.go @@ -2,9 +2,10 @@ package user import ( "context" + "net/http" "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const url = "https://api.mercadopago.com/users/me" @@ -29,7 +30,11 @@ func NewClient(c *config.Config) Client { } func (c *client) Get(ctx context.Context) (*Response, error) { - result, err := baseclient.Get[*Response](ctx, c.cfg, url) + callData := httpclient.CallData{ + Method: http.MethodGet, + URL: url, + } + result, err := httpclient.Run[*Response](ctx, c.cfg, callData) if err != nil { return nil, err } diff --git a/test/integration/refund/refund_test.go b/test/integration/refund/refund_test.go index 5d68e202..35c11326 100644 --- a/test/integration/refund/refund_test.go +++ b/test/integration/refund/refund_test.go @@ -84,7 +84,7 @@ func TestRefund(t *testing.T) { partialAmount := req.TransactionAmount - 5.0 refundClient := refund.NewClient(cfg) - ref, err := refundClient.CreatePartialRefund(context.Background(), partialAmount, pay.ID) + ref, err := refundClient.CreatePartialRefund(context.Background(), pay.ID, partialAmount) if ref == nil { t.Error("refund can't be nil") } @@ -175,7 +175,7 @@ func TestRefund(t *testing.T) { // Partial refund refundClient := refund.NewClient(cfg) - ref, err := refundClient.CreatePartialRefund(context.Background(), partialAmount, pay.ID) + ref, err := refundClient.CreatePartialRefund(context.Background(), pay.ID, partialAmount) if ref == nil { t.Error("refund can't be nil") } From aea02512e82b6e3ebaef31a871d739ea1cc16967 Mon Sep 17 00:00:00 2001 From: gabs Date: Fri, 1 Mar 2024 16:19:33 -0300 Subject: [PATCH 03/19] Remove useless tests --- pkg/cardtoken/client_test.go | 24 ++-- pkg/customer/client_test.go | 11 -- pkg/payment/client_test.go | 208 ------------------------------- pkg/paymentmethod/client_test.go | 32 ----- pkg/refund/client_test.go | 128 ------------------- pkg/user/client_test.go | 32 ----- 6 files changed, 12 insertions(+), 423 deletions(-) diff --git a/pkg/cardtoken/client_test.go b/pkg/cardtoken/client_test.go index f226352b..0b07f327 100644 --- a/pkg/cardtoken/client_test.go +++ b/pkg/cardtoken/client_test.go @@ -35,16 +35,12 @@ func TestCreate(t *testing.T) { wantErr string }{ { - name: "should_create_card_token", + name: "should_fail_create_card_token", fields: fields{ cfg: &config.Config{ Requester: &httpclient.Mock{ DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader(string(cardTokenResponse)) - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil + return nil, fmt.Errorf("some error") }, }, }, @@ -52,16 +48,20 @@ func TestCreate(t *testing.T) { args: args{ ctx: context.Background(), }, - want: mockCardToken(), - wantErr: "", + want: nil, + wantErr: "transport level error: some error", }, { - name: "should_fail_create_card_token", + name: "should_create_card_token", fields: fields{ cfg: &config.Config{ Requester: &httpclient.Mock{ DoMock: func(req *http.Request) (*http.Response, error) { - return nil, fmt.Errorf("some error") + stringReader := strings.NewReader(string(cardTokenResponse)) + stringReadCloser := io.NopCloser(stringReader) + return &http.Response{ + Body: stringReadCloser, + }, nil }, }, }, @@ -69,8 +69,8 @@ func TestCreate(t *testing.T) { args: args{ ctx: context.Background(), }, - want: nil, - wantErr: "transport level error: some error", + want: mockCardToken(), + wantErr: "", }, } for _, tt := range tests { diff --git a/pkg/customer/client_test.go b/pkg/customer/client_test.go index 245f6a42..43e19956 100644 --- a/pkg/customer/client_test.go +++ b/pkg/customer/client_test.go @@ -42,17 +42,6 @@ func TestCreate(t *testing.T) { want *Response wantErr string }{ - { - name: "should_return_error_when_creating_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_return_response", fields: fields{ diff --git a/pkg/payment/client_test.go b/pkg/payment/client_test.go index 1379aa84..120db585 100644 --- a/pkg/payment/client_test.go +++ b/pkg/payment/client_test.go @@ -49,33 +49,6 @@ func TestCreate(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_marshal_dto", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - dto: Request{ - Metadata: map[string]any{ - "fail": make(chan int), - }, - }, - }, - want: nil, - wantErr: "error creating request: error marshaling request body: json: unsupported type: chan int", - }, - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -93,27 +66,6 @@ func TestCreate(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -176,17 +128,6 @@ func TestSearch(t *testing.T) { want *SearchResponse wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -204,27 +145,6 @@ func TestSearch(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -304,17 +224,6 @@ func TestGet(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -332,27 +241,6 @@ func TestGet(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -415,17 +303,6 @@ func TestCancel(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -443,27 +320,6 @@ func TestCancel(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -526,17 +382,6 @@ func TestCapture(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -554,27 +399,6 @@ func TestCapture(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -638,17 +462,6 @@ func TestCaptureAmount(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -666,27 +479,6 @@ func TestCaptureAmount(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ diff --git a/pkg/paymentmethod/client_test.go b/pkg/paymentmethod/client_test.go index 359f2a21..6d485a22 100644 --- a/pkg/paymentmethod/client_test.go +++ b/pkg/paymentmethod/client_test.go @@ -33,17 +33,6 @@ func TestList(t *testing.T) { want []Response wantErr string }{ - { - name: "should_return_error_when_creating_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_return_error_when_send_request", fields: fields{ @@ -61,27 +50,6 @@ func TestList(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_return_error_unmarshal_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_formatted_response", fields: fields{ diff --git a/pkg/refund/client_test.go b/pkg/refund/client_test.go index d2d54fdc..fe153c98 100644 --- a/pkg/refund/client_test.go +++ b/pkg/refund/client_test.go @@ -37,17 +37,6 @@ func TestCreate(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -65,27 +54,6 @@ func TestCreate(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -144,17 +112,6 @@ func TestCreatePartialRefund(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -172,27 +129,6 @@ func TestCreatePartialRefund(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -250,17 +186,6 @@ func TestGet(t *testing.T) { want *Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -278,27 +203,6 @@ func TestGet(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ @@ -356,17 +260,6 @@ func TestList(t *testing.T) { want []Response wantErr string }{ - { - name: "should_fail_to_create_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_fail_to_send_request", fields: fields{ @@ -384,27 +277,6 @@ func TestList(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_fail_to_unmarshaling_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ diff --git a/pkg/user/client_test.go b/pkg/user/client_test.go index 6230f71a..88869572 100644 --- a/pkg/user/client_test.go +++ b/pkg/user/client_test.go @@ -33,17 +33,6 @@ func TestGet(t *testing.T) { want *Response wantErr string }{ - { - name: "should_return_error_when_creating_request", - fields: fields{ - config: nil, - }, - args: args{ - ctx: nil, - }, - want: nil, - wantErr: "error creating request: net/http: nil Context", - }, { name: "should_return_error_when_send_request", fields: fields{ @@ -61,27 +50,6 @@ func TestGet(t *testing.T) { want: nil, wantErr: "transport level error: some error", }, - { - name: "should_return_error_unmarshal_response", - fields: fields{ - config: &config.Config{ - Requester: &httpclient.Mock{ - DoMock: func(req *http.Request) (*http.Response, error) { - stringReader := strings.NewReader("invalid json") - stringReadCloser := io.NopCloser(stringReader) - return &http.Response{ - Body: stringReadCloser, - }, nil - }, - }, - }, - }, - args: args{ - ctx: context.Background(), - }, - want: nil, - wantErr: "invalid character 'i' looking for beginning of value", - }, { name: "should_return_response", fields: fields{ From 1879d81a4bc096e5f6f1c1efb7b9ff0513529c67 Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 18:42:29 -0300 Subject: [PATCH 04/19] Update tests --- examples/apis/merchantorder/update/main.go | 5 +- pkg/customer/client.go | 1 + pkg/merchantorder/client.go | 2 +- pkg/point/client.go | 10 +- pkg/preference/client.go | 2 +- test/card_token.go | 31 ++++ test/config.go | 15 ++ ...ntorder_test.go => merchant_order_test.go} | 5 +- test/integration/payment/payment_test.go | 138 ++++++++++-------- test/integration/refund/refund_test.go | 109 +++++++------- 10 files changed, 195 insertions(+), 123 deletions(-) create mode 100644 test/card_token.go create mode 100644 test/config.go rename test/integration/merchantorder/{merchantorder_test.go => merchant_order_test.go} (98%) diff --git a/examples/apis/merchantorder/update/main.go b/examples/apis/merchantorder/update/main.go index 7490c5cc..42dc2b12 100644 --- a/examples/apis/merchantorder/update/main.go +++ b/examples/apis/merchantorder/update/main.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "time" "github.com/google/uuid" "github.com/mercadopago/sdk-go/pkg/config" @@ -11,7 +12,7 @@ import ( ) func main() { - accessToken := "{{ACCESS_TOKEN}}" + accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" cfg, err := config.New(accessToken) if err != nil { @@ -81,6 +82,8 @@ func main() { }, } + time.Sleep(time.Second * 10) + order, err = client.Update(context.Background(), req, order.ID) if err != nil { fmt.Println(err) diff --git a/pkg/customer/client.go b/pkg/customer/client.go index 5071bb03..3c3f3cf3 100644 --- a/pkg/customer/client.go +++ b/pkg/customer/client.go @@ -103,6 +103,7 @@ func (c *client) Update(ctx context.Context, id string, request Request) (*Respo } callData := httpclient.CallData{ + Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, diff --git a/pkg/merchantorder/client.go b/pkg/merchantorder/client.go index 88ebff35..a2715313 100644 --- a/pkg/merchantorder/client.go +++ b/pkg/merchantorder/client.go @@ -12,7 +12,7 @@ import ( const ( urlBase = "https://api.mercadopago.com/merchant_orders" urlSearch = urlBase + "/search" - urlWithID = urlBase + "/:id" + urlWithID = urlBase + "/{id}" ) // Client contains the methods to interact with the Merchant orders API. diff --git a/pkg/point/client.go b/pkg/point/client.go index 5a3ef4fa..577a6909 100644 --- a/pkg/point/client.go +++ b/pkg/point/client.go @@ -10,11 +10,11 @@ import ( const ( urlBase = "https://api.mercadopago.com/point" - urlDevices = urlBase + "/integration-api/devices/" - urlPaymentIntent = urlDevices + ":device_id/payment-intents" - urlPaymentIntentGet = urlBase + "/integration-api/payment-intents/:payment_intent_id" - urlPaymentIntentCancel = urlDevices + ":device_id/payment-intents/:payment_intent_id" - urlDevicesWithID = urlDevices + ":device_id" + urlDevices = urlBase + "/integration-api/devices" + urlPaymentIntent = urlDevices + "/{device_id}/payment-intents" + urlPaymentIntentGet = urlBase + "/integration-api/payment-intents/{payment_intent_id}" + urlPaymentIntentCancel = urlDevices + "/{device_id}/payment-intents/{payment_intent_id}" + urlDevicesWithID = urlDevices + "/{device_id}" ) // client is the implementation of Client. diff --git a/pkg/preference/client.go b/pkg/preference/client.go index ad8d1687..d911348e 100644 --- a/pkg/preference/client.go +++ b/pkg/preference/client.go @@ -11,7 +11,7 @@ import ( const ( urlBase = "https://api.mercadopago.com/checkout/preferences" urlSearch = urlBase + "/search" - urlWithID = urlBase + "/:id" + urlWithID = urlBase + "/{id}" ) // Client contains the methods to interact with the Preference API. diff --git a/test/card_token.go b/test/card_token.go new file mode 100644 index 00000000..13520a22 --- /dev/null +++ b/test/card_token.go @@ -0,0 +1,31 @@ +package test + +import ( + "context" + + "github.com/mercadopago/sdk-go/pkg/cardtoken" +) + +func GenerateCardToken(ctx context.Context, client cardtoken.Client) (string, error) { + req := cardtoken.Request{ + Cardholder: &cardtoken.Cardholder{ + Identification: &cardtoken.Identification{ + Number: "01234567890", + Type: "CPF", + }, + Name: "APRO", + }, + SiteID: "MLB", + CardNumber: "5031433215406351", + ExpirationYear: "2025", + ExpirationMonth: "11", + SecurityCode: "123", + } + + result, err := client.Create(context.Background(), req) + if err != nil { + return "", err + } + + return result.ID, nil +} diff --git a/test/config.go b/test/config.go new file mode 100644 index 00000000..ee720b12 --- /dev/null +++ b/test/config.go @@ -0,0 +1,15 @@ +package test + +import ( + "os" + + "github.com/mercadopago/sdk-go/pkg/config" +) + +func Config() *config.Config { + cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + if err != nil { + panic(err) + } + return cfg +} diff --git a/test/integration/merchantorder/merchantorder_test.go b/test/integration/merchantorder/merchant_order_test.go similarity index 98% rename from test/integration/merchantorder/merchantorder_test.go rename to test/integration/merchantorder/merchant_order_test.go index 729a86da..1ecf7177 100644 --- a/test/integration/merchantorder/merchantorder_test.go +++ b/test/integration/merchantorder/merchant_order_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "testing" + "time" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/merchantorder" @@ -124,7 +125,7 @@ func TestMerchantOrder(t *testing.T) { client := merchantorder.NewClient(cfg) order, err := client.Create(context.Background(), createReq) - if order == nil { + if order == nil || order.ID == 0 { t.Error("merchant order can't be nil") return } @@ -144,6 +145,8 @@ func TestMerchantOrder(t *testing.T) { }, } + time.Sleep(time.Second * 5) + order, err = client.Update(context.Background(), req, order.ID) if order == nil { fmt.Println(err) diff --git a/test/integration/payment/payment_test.go b/test/integration/payment/payment_test.go index 8a6a5e94..bd694c4a 100644 --- a/test/integration/payment/payment_test.go +++ b/test/integration/payment/payment_test.go @@ -3,38 +3,36 @@ package integration import ( "context" "fmt" - "os" "testing" "github.com/google/uuid" + "github.com/mercadopago/sdk-go/pkg/cardtoken" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" + "github.com/mercadopago/sdk-go/test" +) + +var ( + cfg *config.Config = test.Config() + paymentClient = payment.NewClient(cfg) + cardTokenClient = cardtoken.NewClient(cfg) ) func TestPayment(t *testing.T) { t.Run("should_create_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) - if err != nil { - t.Fatal(err) - } - - client := payment.NewClient(cfg) + ctx := context.Background() req := payment.Request{ TransactionAmount: 105.1, PaymentMethodID: "pix", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, } - pay, err := client.Create(context.Background(), req) - if pay == nil { + pay, err := paymentClient.Create(ctx, req) + if pay == nil || pay.ID == 0 { t.Error("payment can't be nil") - return - } - if pay.ID == 0 { - t.Error("id can't be nil") } if err != nil { t.Errorf(err.Error()) @@ -42,10 +40,7 @@ func TestPayment(t *testing.T) { }) t.Run("should_search_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) - if err != nil { - t.Fatal(err) - } + ctx := context.Background() req := payment.SearchRequest{ Filters: map[string]string{ @@ -53,10 +48,9 @@ func TestPayment(t *testing.T) { }, } - client := payment.NewClient(cfg) - paymentSearch, err := client.Search(context.Background(), req) - if paymentSearch == nil { - t.Error("paymentSearch can't be nil") + result, err := paymentClient.Search(ctx, req) + if result == nil { + t.Error("result can't be nil") } if err != nil { t.Errorf(err.Error()) @@ -64,36 +58,29 @@ func TestPayment(t *testing.T) { }) t.Run("should_get_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) - if err != nil { - t.Fatal(err) - } + ctx := context.Background() - client := payment.NewClient(cfg) + // Create payment. paymentRequest := payment.Request{ TransactionAmount: 105.1, PaymentMethodID: "pix", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, } - pay, err := client.Create(context.Background(), paymentRequest) - if pay == nil { + pay, err := paymentClient.Create(ctx, paymentRequest) + if pay == nil || pay.ID == 0 { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) } - pay, err = client.Get(context.Background(), pay.ID) + // Get payment. + pay, err = paymentClient.Get(ctx, pay.ID) if pay == nil { t.Error("payment can't be nil") - return - } - if pay.ID == 0 { - t.Error("id can't be nil") } if err != nil { t.Errorf(err.Error()) @@ -101,93 +88,116 @@ func TestPayment(t *testing.T) { }) t.Run("should_cancel_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) - if err != nil { - t.Fatal(err) - } + ctx := context.Background() - client := payment.NewClient(cfg) + // Create payment. req := payment.Request{ TransactionAmount: 105.1, PaymentMethodID: "pix", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, } - pay, err := client.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) + return } - pay, err = client.Cancel(context.Background(), pay.ID) + // Cancel payment. + pay, err = paymentClient.Cancel(ctx, pay.ID) if pay == nil { t.Error("payment can't be nil") - return } - if pay.ID == 0 { - t.Error("id can't be nil") + if pay != nil && pay.Status != "cancelled" { + t.Error("payment should be cancelled, but is wasn't") } if err != nil { t.Errorf(err.Error()) } }) - // We should validate how to test capture and capture amount. t.Run("should_capture_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) if err != nil { - t.Fatal(err) + t.Error("fail to generate card token", err) } - client := payment.NewClient(cfg) - // Create payment. req := payment.Request{ TransactionAmount: 105.1, - PaymentMethodID: "visa", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, - // Need to get a token from a card. - Token: "", + Token: token, Installments: 1, Capture: false, } - pay, err := client.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) } - pay, err = client.Capture(context.Background(), pay.ID) + // Capture payment. + pay, err = paymentClient.Capture(ctx, pay.ID) if pay == nil { t.Error("payment can't be nil") } + if pay != nil && pay.Status != "approved" { + t.Error("payment should be approved, but is wasn't") + } if err != nil { t.Errorf(err.Error()) } }) t.Run("should_capture_amount_payment", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) + if err != nil { + t.Error("fail to generate card token", err) + } + + // Create payment. + req := payment.Request{ + TransactionAmount: 105.1, + Payer: &payment.PayerRequest{ + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), + }, + Token: token, + Installments: 1, + Capture: false, + } + pay, err := paymentClient.Create(ctx, req) + if pay == nil { + t.Error("payment can't be nil") + } if err != nil { - t.Fatal(err) + t.Errorf(err.Error()) + return } - client := payment.NewClient(cfg) - pay, err := client.CaptureAmount(context.Background(), 123, 100.1) + // Capture payment. + pay, err = paymentClient.CaptureAmount(ctx, pay.ID, 100.1) if pay == nil { t.Error("payment can't be nil") } + if pay != nil && pay.Status != "approved" { + t.Error("payment should be approved, but is wasn't") + } if err != nil { t.Errorf(err.Error()) } diff --git a/test/integration/refund/refund_test.go b/test/integration/refund/refund_test.go index 35c11326..1a760a17 100644 --- a/test/integration/refund/refund_test.go +++ b/test/integration/refund/refund_test.go @@ -3,47 +3,55 @@ package integration import ( "context" "fmt" - "os" "testing" "github.com/google/uuid" + "github.com/mercadopago/sdk-go/pkg/cardtoken" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" "github.com/mercadopago/sdk-go/pkg/refund" + "github.com/mercadopago/sdk-go/test" +) + +var ( + cfg *config.Config = test.Config() + paymentClient = payment.NewClient(cfg) + cardTokenClient = cardtoken.NewClient(cfg) + refundClient = refund.NewClient(cfg) ) func TestRefund(t *testing.T) { t.Run("should_create_refund", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) if err != nil { - t.Fatal(err) + t.Error("fail to generate card token", err) } // Create payment. req := payment.Request{ TransactionAmount: 105.1, - PaymentMethodID: "visa", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, - // Need to get a token from a card. - Token: "", + Token: token, Installments: 1, Capture: false, } - paymentClient := payment.NewClient(cfg) - pay, err := paymentClient.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) + return } - refundClient := refund.NewClient(cfg) - ref, err := refundClient.Create(context.Background(), pay.ID) + // Create refund. + ref, err := refundClient.Create(ctx, pay.ID) if ref == nil { t.Error("refund can't be nil") } @@ -53,38 +61,38 @@ func TestRefund(t *testing.T) { }) t.Run("should_create_partial_refund", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) if err != nil { - t.Fatal(err) + t.Error("fail to generate card token", err) } // Create payment. req := payment.Request{ TransactionAmount: 105.1, - PaymentMethodID: "visa", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, - // Need to get a token from a card. - Token: "", + Token: token, Installments: 1, Capture: false, } - paymentClient := payment.NewClient(cfg) - pay, err := paymentClient.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) + return } - partialAmount := req.TransactionAmount - 5.0 + // Create partial refund. + partialAmount := pay.TransactionAmount - 5.0 - refundClient := refund.NewClient(cfg) - ref, err := refundClient.CreatePartialRefund(context.Background(), pay.ID, partialAmount) + ref, err := refundClient.CreatePartialRefund(ctx, pay.ID, partialAmount) if ref == nil { t.Error("refund can't be nil") } @@ -94,36 +102,36 @@ func TestRefund(t *testing.T) { }) t.Run("should_get_refund", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) if err != nil { - t.Fatal(err) + t.Error("fail to generate card token", err) } // Create payment. req := payment.Request{ TransactionAmount: 105.1, - PaymentMethodID: "visa", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, - // Need to get a token from a card. - Token: "", + Token: token, Installments: 1, Capture: false, } - paymentClient := payment.NewClient(cfg) - pay, err := paymentClient.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") - return } if err != nil { t.Errorf(err.Error()) + return } - refundClient := refund.NewClient(cfg) - ref, err := refundClient.Create(context.Background(), pay.ID) + // Create refund. + ref, err := refundClient.Create(ctx, pay.ID) if ref == nil { t.Error("refund can't be nil") return @@ -132,7 +140,8 @@ func TestRefund(t *testing.T) { t.Errorf(err.Error()) } - ref, err = refundClient.Get(context.Background(), pay.ID, ref.ID) + // Get refund. + ref, err = refundClient.Get(ctx, pay.ID, ref.ID) if err != nil { t.Errorf(err.Error()) } @@ -143,26 +152,26 @@ func TestRefund(t *testing.T) { }) t.Run("should_list_refund", func(t *testing.T) { - cfg, err := config.New(os.Getenv("ACCESS_TOKEN")) + ctx := context.Background() + + // Generate token. + token, err := test.GenerateCardToken(ctx, cardTokenClient) if err != nil { - t.Fatal(err) + t.Error("fail to generate card token", err) } // Create payment. req := payment.Request{ TransactionAmount: 105.1, - PaymentMethodID: "visa", Payer: &payment.PayerRequest{ - Email: fmt.Sprintf("gabs_%s@testuser.com", uuid.New()), + Email: fmt.Sprintf("gabs_%s@meli.com", uuid.New()), }, - // Need to get a token from a card. - Token: "", + Token: token, Installments: 1, Capture: false, } - paymentClient := payment.NewClient(cfg) - pay, err := paymentClient.Create(context.Background(), req) + pay, err := paymentClient.Create(ctx, req) if pay == nil { t.Error("payment can't be nil") return @@ -171,11 +180,10 @@ func TestRefund(t *testing.T) { t.Errorf(err.Error()) } + // Create partial refund. partialAmount := req.TransactionAmount - 5.0 - // Partial refund - refundClient := refund.NewClient(cfg) - ref, err := refundClient.CreatePartialRefund(context.Background(), pay.ID, partialAmount) + ref, err := refundClient.CreatePartialRefund(ctx, pay.ID, partialAmount) if ref == nil { t.Error("refund can't be nil") } @@ -183,8 +191,8 @@ func TestRefund(t *testing.T) { t.Errorf(err.Error()) } - // Total refund - ref, err = refundClient.Create(context.Background(), pay.ID) + // Create total refund. + ref, err = refundClient.Create(ctx, pay.ID) if ref == nil { t.Error("refund can't be nil") } @@ -192,7 +200,8 @@ func TestRefund(t *testing.T) { t.Errorf(err.Error()) } - refunds, err := refundClient.List(context.Background(), pay.ID) + // List refunds. + refunds, err := refundClient.List(ctx, pay.ID) if err != nil { t.Errorf(err.Error()) } From 75fd48d29b58b05d3fdbe3c52d6ad4eac27a363d Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 18:44:15 -0300 Subject: [PATCH 05/19] Switch credentials --- examples/apis/customer/search/main.go | 4 ++-- examples/apis/merchantorder/update/main.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/apis/customer/search/main.go b/examples/apis/customer/search/main.go index c026ca35..2663eb81 100644 --- a/examples/apis/customer/search/main.go +++ b/examples/apis/customer/search/main.go @@ -9,7 +9,7 @@ import ( ) func main() { - accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" + accessToken := "{{ACCESS_TOKEN}}" cfg, err := config.New(accessToken) if err != nil { @@ -19,7 +19,7 @@ func main() { req := customer.SearchRequest{ Filters: map[string]string{ - "EMAIL": "akdsokdoakdoasakdoas@testuser.com", + "EMAIL": "{{EMAIL}}", }, } diff --git a/examples/apis/merchantorder/update/main.go b/examples/apis/merchantorder/update/main.go index 42dc2b12..5a28b222 100644 --- a/examples/apis/merchantorder/update/main.go +++ b/examples/apis/merchantorder/update/main.go @@ -12,7 +12,7 @@ import ( ) func main() { - accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" + accessToken := "{{ACCESS_TOKEN}}" cfg, err := config.New(accessToken) if err != nil { From bfe89830167e191254bc4416323d12323951e08f Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 18:49:58 -0300 Subject: [PATCH 06/19] Remove useless sleep --- examples/apis/merchantorder/update/main.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/apis/merchantorder/update/main.go b/examples/apis/merchantorder/update/main.go index 5a28b222..1de5cc19 100644 --- a/examples/apis/merchantorder/update/main.go +++ b/examples/apis/merchantorder/update/main.go @@ -3,7 +3,6 @@ package main import ( "context" "fmt" - "time" "github.com/google/uuid" "github.com/mercadopago/sdk-go/pkg/config" @@ -12,7 +11,7 @@ import ( ) func main() { - accessToken := "{{ACCESS_TOKEN}}" + accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" cfg, err := config.New(accessToken) if err != nil { @@ -82,7 +81,7 @@ func main() { }, } - time.Sleep(time.Second * 10) + // time.Sleep(time.Second * 10) order, err = client.Update(context.Background(), req, order.ID) if err != nil { From 2117d98e312fb44d7297c1a31c883026fb6b7971 Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 19:08:48 -0300 Subject: [PATCH 07/19] Fix tests --- examples/apis/point/create/main.go | 2 +- test/integration/payment/payment_test.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/apis/point/create/main.go b/examples/apis/point/create/main.go index fad4e433..52c19c7c 100644 --- a/examples/apis/point/create/main.go +++ b/examples/apis/point/create/main.go @@ -20,7 +20,7 @@ func main() { req := point.CreateRequest{ Amount: 1500, Description: "your payment intent description", - AdditionalInfo: &point.AdditionalInfo{ + AdditionalInfo: &point.AdditionalInfoRequest{ PrintOnTerminal: false, ExternalReference: "4561ads-das4das4-das4754-das456", }, diff --git a/test/integration/payment/payment_test.go b/test/integration/payment/payment_test.go index bd694c4a..0386f7cf 100644 --- a/test/integration/payment/payment_test.go +++ b/test/integration/payment/payment_test.go @@ -147,6 +147,7 @@ func TestPayment(t *testing.T) { } if err != nil { t.Errorf(err.Error()) + return } // Capture payment. From ba74fd4b3d7adb4db2b35509899d68eead337e56 Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 19:42:41 -0300 Subject: [PATCH 08/19] Remove mock file --- pkg/cardtoken/client_test.go | 31 +++++++++++ pkg/cardtoken/mock.go | 52 ------------------- .../{cardtoken_test.go => card_token_test.go} | 18 ++++++- 3 files changed, 48 insertions(+), 53 deletions(-) delete mode 100644 pkg/cardtoken/mock.go rename test/integration/cardtoken/{cardtoken_test.go => card_token_test.go} (53%) diff --git a/pkg/cardtoken/client_test.go b/pkg/cardtoken/client_test.go index 0b07f327..817e6983 100644 --- a/pkg/cardtoken/client_test.go +++ b/pkg/cardtoken/client_test.go @@ -9,6 +9,7 @@ import ( "reflect" "strings" "testing" + "time" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/internal/httpclient" @@ -93,3 +94,33 @@ func TestCreate(t *testing.T) { }) } } + +func mockCardToken() *Response { + return &Response{ + ID: "3d40b34eb41a6d0923e5bc545927c2e9", + FirstSixDigits: "503143", + ExpirationMonth: 11, + ExpirationYear: 2025, + LastFourDigits: "6351", + Cardholder: CardholderResponse{ + Identification: IdentificationResponse{ + Number: "70383868084", + Type: "CPF", + }, + Name: "MASTER TEST", + }, + Status: "active", + DateCreated: parseDate("2024-02-08T09:05:42.725-04:00"), + DateLastUpdated: parseDate("2024-02-08T09:05:42.725-04:00"), + DateDue: parseDate("2024-02-16T09:05:42.725-04:00"), + LuhnValidation: true, + LiveMode: false, + CardNumberLength: 16, + SecurityCodeLength: 3, + } +} + +func parseDate(s string) *time.Time { + d, _ := time.Parse(time.RFC3339, s) + return &d +} diff --git a/pkg/cardtoken/mock.go b/pkg/cardtoken/mock.go deleted file mode 100644 index 906c4a32..00000000 --- a/pkg/cardtoken/mock.go +++ /dev/null @@ -1,52 +0,0 @@ -package cardtoken - -import ( - "time" -) - -func mockCardToken() *Response { - return &Response{ - ID: "3d40b34eb41a6d0923e5bc545927c2e9", - FirstSixDigits: "503143", - ExpirationMonth: 11, - ExpirationYear: 2025, - LastFourDigits: "6351", - Cardholder: CardholderResponse{ - Identification: IdentificationResponse{ - Number: "70383868084", - Type: "CPF", - }, - Name: "MASTER TEST", - }, - Status: "active", - DateCreated: parseDate("2024-02-08T09:05:42.725-04:00"), - DateLastUpdated: parseDate("2024-02-08T09:05:42.725-04:00"), - DateDue: parseDate("2024-02-16T09:05:42.725-04:00"), - LuhnValidation: true, - LiveMode: false, - CardNumberLength: 16, - SecurityCodeLength: 3, - } -} - -func MockCardTokenRequest() Request { - return Request{ - SiteID: "Teste", - CardNumber: "5031433215406351", - ExpirationMonth: "11", - ExpirationYear: "2025", - SecurityCode: "123", - Cardholder: &Cardholder{ - Identification: &Identification{ - Type: "CPF", - Number: "70383868084", - }, - Name: "MASTER TEST", - }, - } -} - -func parseDate(s string) *time.Time { - d, _ := time.Parse(time.RFC3339, s) - return &d -} diff --git a/test/integration/cardtoken/cardtoken_test.go b/test/integration/cardtoken/card_token_test.go similarity index 53% rename from test/integration/cardtoken/cardtoken_test.go rename to test/integration/cardtoken/card_token_test.go index 4616de99..d9c79d10 100644 --- a/test/integration/cardtoken/cardtoken_test.go +++ b/test/integration/cardtoken/card_token_test.go @@ -17,7 +17,23 @@ func TestCardToken(t *testing.T) { } client := cardtoken.NewClient(cfg) - cardToken, err := client.Create(context.Background(), cardtoken.MockCardTokenRequest()) + + request := cardtoken.Request{ + SiteID: "Teste", + CardNumber: "5031433215406351", + ExpirationMonth: "11", + ExpirationYear: "2025", + SecurityCode: "123", + Cardholder: &cardtoken.Cardholder{ + Identification: &cardtoken.Identification{ + Type: "CPF", + Number: "70383868084", + }, + Name: "MASTER TEST", + }, + } + + cardToken, err := client.Create(context.Background(), request) if cardToken == nil { t.Error("cardToken can't be nil") From 4bf127b553dc1a59d058a7a379e8a89beaab16bc Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 19:46:38 -0300 Subject: [PATCH 09/19] Add customer tests --- pkg/customer/client_test.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/pkg/customer/client_test.go b/pkg/customer/client_test.go index 43e19956..76e32ce9 100644 --- a/pkg/customer/client_test.go +++ b/pkg/customer/client_test.go @@ -2,6 +2,7 @@ package customer import ( "context" + "fmt" "io" "net/http" "os" @@ -42,6 +43,23 @@ func TestCreate(t *testing.T) { want *Response wantErr string }{ + { + name: "should_fail_to_send_request", + fields: fields{ + config: &config.Config{ + Requester: &httpclient.Mock{ + DoMock: func(req *http.Request) (*http.Response, error) { + return nil, fmt.Errorf("some error") + }, + }, + }, + }, + args: args{ + ctx: context.Background(), + }, + want: nil, + wantErr: "transport level error: some error", + }, { name: "should_return_response", fields: fields{ @@ -106,6 +124,23 @@ func TestSearch(t *testing.T) { want *SearchResponse wantErr string }{ + { + name: "should_fail_to_send_request", + fields: fields{ + config: &config.Config{ + Requester: &httpclient.Mock{ + DoMock: func(req *http.Request) (*http.Response, error) { + return nil, fmt.Errorf("some error") + }, + }, + }, + }, + args: args{ + ctx: context.Background(), + }, + want: nil, + wantErr: "transport level error: some error", + }, { name: "should_return_response", fields: fields{ From 3590beda3439189e7bb6591b8862247a32916725 Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 19:50:30 -0300 Subject: [PATCH 10/19] Cover customer search_request.go --- pkg/customer/client_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/customer/client_test.go b/pkg/customer/client_test.go index 76e32ce9..2aa2ab34 100644 --- a/pkg/customer/client_test.go +++ b/pkg/customer/client_test.go @@ -159,7 +159,11 @@ func TestSearch(t *testing.T) { args: args{ ctx: context.Background(), request: SearchRequest{ - Limit: "10", + Filters: map[string]string{ + "EMAIL": "test_user_30851371@testuser.com", + }, + Limit: "10", + Offset: "10", }, }, want: &SearchResponse{ From 5e886dea88a51966c6a0e9b59438f405595330e6 Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 19:54:06 -0300 Subject: [PATCH 11/19] Add payment search_request.go test --- pkg/payment/client_test.go | 9 +++++++-- resources/mocks/payment/search_response.json | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/pkg/payment/client_test.go b/pkg/payment/client_test.go index 120db585..8324c522 100644 --- a/pkg/payment/client_test.go +++ b/pkg/payment/client_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + "github.com/google/uuid" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) @@ -163,14 +164,18 @@ func TestSearch(t *testing.T) { args: args{ ctx: context.Background(), dto: SearchRequest{ - Limit: "30", + Filters: map[string]string{ + "ExTernal_RefeRENCE": uuid.NewString(), + }, + Limit: "30", + Offset: "10", }, }, want: &SearchResponse{ Paging: PagingResponse{ Total: 2, Limit: 30, - Offset: 0, + Offset: 10, }, Results: []Response{ { diff --git a/resources/mocks/payment/search_response.json b/resources/mocks/payment/search_response.json index 6f8d8ef2..484f34dc 100644 --- a/resources/mocks/payment/search_response.json +++ b/resources/mocks/payment/search_response.json @@ -2,7 +2,7 @@ "paging": { "total": 2, "limit": 30, - "offset": 0 + "offset": 10 }, "results": [ { From cc20bca84ec488a44588d557879bdceedc19936c Mon Sep 17 00:00:00 2001 From: gabs Date: Mon, 4 Mar 2024 20:17:02 -0300 Subject: [PATCH 12/19] PR adjusts --- examples/apis/merchantorder/update/main.go | 4 +--- test/integration/merchantorder/merchant_order_test.go | 3 --- test/integration/payment/payment_test.go | 7 +++---- test/integration/refund/refund_test.go | 9 ++++----- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/examples/apis/merchantorder/update/main.go b/examples/apis/merchantorder/update/main.go index 1de5cc19..7490c5cc 100644 --- a/examples/apis/merchantorder/update/main.go +++ b/examples/apis/merchantorder/update/main.go @@ -11,7 +11,7 @@ import ( ) func main() { - accessToken := "TEST-4718610619866357-092020-f30ef41ea2a9e7ad0fa7bc101b5508af-751574177" + accessToken := "{{ACCESS_TOKEN}}" cfg, err := config.New(accessToken) if err != nil { @@ -81,8 +81,6 @@ func main() { }, } - // time.Sleep(time.Second * 10) - order, err = client.Update(context.Background(), req, order.ID) if err != nil { fmt.Println(err) diff --git a/test/integration/merchantorder/merchant_order_test.go b/test/integration/merchantorder/merchant_order_test.go index 1ecf7177..ee67488f 100644 --- a/test/integration/merchantorder/merchant_order_test.go +++ b/test/integration/merchantorder/merchant_order_test.go @@ -5,7 +5,6 @@ import ( "fmt" "os" "testing" - "time" "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/merchantorder" @@ -145,8 +144,6 @@ func TestMerchantOrder(t *testing.T) { }, } - time.Sleep(time.Second * 5) - order, err = client.Update(context.Background(), req, order.ID) if order == nil { fmt.Println(err) diff --git a/test/integration/payment/payment_test.go b/test/integration/payment/payment_test.go index 0386f7cf..1d1770a1 100644 --- a/test/integration/payment/payment_test.go +++ b/test/integration/payment/payment_test.go @@ -7,15 +7,14 @@ import ( "github.com/google/uuid" "github.com/mercadopago/sdk-go/pkg/cardtoken" - "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" "github.com/mercadopago/sdk-go/test" ) var ( - cfg *config.Config = test.Config() - paymentClient = payment.NewClient(cfg) - cardTokenClient = cardtoken.NewClient(cfg) + cfg = test.Config() + paymentClient = payment.NewClient(cfg) + cardTokenClient = cardtoken.NewClient(cfg) ) func TestPayment(t *testing.T) { diff --git a/test/integration/refund/refund_test.go b/test/integration/refund/refund_test.go index 1a760a17..d7cc0640 100644 --- a/test/integration/refund/refund_test.go +++ b/test/integration/refund/refund_test.go @@ -7,17 +7,16 @@ import ( "github.com/google/uuid" "github.com/mercadopago/sdk-go/pkg/cardtoken" - "github.com/mercadopago/sdk-go/pkg/config" "github.com/mercadopago/sdk-go/pkg/payment" "github.com/mercadopago/sdk-go/pkg/refund" "github.com/mercadopago/sdk-go/test" ) var ( - cfg *config.Config = test.Config() - paymentClient = payment.NewClient(cfg) - cardTokenClient = cardtoken.NewClient(cfg) - refundClient = refund.NewClient(cfg) + cfg = test.Config() + paymentClient = payment.NewClient(cfg) + cardTokenClient = cardtoken.NewClient(cfg) + refundClient = refund.NewClient(cfg) ) func TestRefund(t *testing.T) { From 34018bab3907c106f6298f52cafdaea49ad630a5 Mon Sep 17 00:00:00 2001 From: gabs Date: Tue, 5 Mar 2024 11:01:45 -0300 Subject: [PATCH 13/19] Change callData to requestData --- pkg/cardtoken/client.go | 4 ++-- pkg/customer/client.go | 16 ++++++++-------- pkg/customercard/client.go | 20 ++++++++++---------- pkg/identificationtype/client.go | 4 ++-- pkg/internal/httpclient/helper.go | 16 ++++++++-------- pkg/merchantorder/client.go | 16 ++++++++-------- pkg/oauth/client.go | 8 ++++---- pkg/payment/client.go | 24 ++++++++++++------------ pkg/paymentmethod/client.go | 4 ++-- pkg/point/client.go | 20 ++++++++++---------- pkg/preference/client.go | 16 ++++++++-------- pkg/refund/client.go | 16 ++++++++-------- pkg/user/client.go | 4 ++-- 13 files changed, 84 insertions(+), 84 deletions(-) diff --git a/pkg/cardtoken/client.go b/pkg/cardtoken/client.go index 55a9783e..7dbc6dce 100644 --- a/pkg/cardtoken/client.go +++ b/pkg/cardtoken/client.go @@ -26,12 +26,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: url, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/customer/client.go b/pkg/customer/client.go index 3c3f3cf3..aa7edc06 100644 --- a/pkg/customer/client.go +++ b/pkg/customer/client.go @@ -50,12 +50,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -66,12 +66,12 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { request.Check() - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ QueryParams: request.Filters, Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -84,12 +84,12 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { "id": id, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -102,13 +102,13 @@ func (c *client) Update(ctx context.Context, id string, request Request) (*Respo "id": id, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/customercard/client.go b/pkg/customercard/client.go index 1d27c20a..2567c74c 100644 --- a/pkg/customercard/client.go +++ b/pkg/customercard/client.go @@ -58,13 +58,13 @@ func (c *client) Create(ctx context.Context, customerID string, request Request) "customer_id": customerID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.config, callData) + result, err := httpclient.Run[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -78,12 +78,12 @@ func (c *client) Get(ctx context.Context, customerID, cardID string) (*Response, "card_id": cardID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, callData) + result, err := httpclient.Run[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -97,13 +97,13 @@ func (c *client) Update(ctx context.Context, customerID, cardID string, request "card_id": cardID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, callData) + result, err := httpclient.Run[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -117,12 +117,12 @@ func (c *client) Delete(ctx context.Context, customerID, cardID string) (*Respon "card_id": cardID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodDelete, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, callData) + result, err := httpclient.Run[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -135,12 +135,12 @@ func (c *client) List(ctx context.Context, customerID string) ([]Response, error "customer_id": customerID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[[]Response](ctx, c.config, callData) + result, err := httpclient.Run[[]Response](ctx, c.config, requestData) if err != nil { return nil, err } diff --git a/pkg/identificationtype/client.go b/pkg/identificationtype/client.go index ad5cae1d..b0f560bc 100644 --- a/pkg/identificationtype/client.go +++ b/pkg/identificationtype/client.go @@ -29,11 +29,11 @@ func NewClient(cfg *config.Config) Client { } func (c *client) List(ctx context.Context) ([]Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) + result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go index 135c3ad0..ab7ea7af 100644 --- a/pkg/internal/httpclient/helper.go +++ b/pkg/internal/httpclient/helper.go @@ -27,7 +27,7 @@ var ( trackingID = fmt.Sprintf("platform:%s,type:SDK%s,so;", runtime.Version(), currentSDKVersion) ) -type CallData struct { +type RequestData struct { Body any PathParams map[string]string QueryParams map[string]string @@ -36,10 +36,10 @@ type CallData struct { URL string } -func Run[T any](ctx context.Context, cfg *config.Config, callData CallData) (T, error) { +func Run[T any](ctx context.Context, cfg *config.Config, requestData RequestData) (T, error) { var result T - req, err := createRequest(ctx, cfg, callData) + req, err := createRequest(ctx, cfg, requestData) if err != nil { return result, err } @@ -52,22 +52,22 @@ func Run[T any](ctx context.Context, cfg *config.Config, callData CallData) (T, return wrapUnmarshal(b, result) } -func createRequest(ctx context.Context, cfg *config.Config, callData CallData) (*http.Request, error) { - body, err := wrapMarshal(callData.Body) +func createRequest(ctx context.Context, cfg *config.Config, requestData RequestData) (*http.Request, error) { + body, err := wrapMarshal(requestData.Body) if err != nil { return nil, err } - req, err := http.NewRequestWithContext(ctx, callData.Method, callData.URL, body) + req, err := http.NewRequestWithContext(ctx, requestData.Method, requestData.URL, body) if err != nil { return nil, fmt.Errorf("error creating request: %w", err) } setHeaders(req, cfg) - if err = setPathParams(req, callData.PathParams); err != nil { + if err = setPathParams(req, requestData.PathParams); err != nil { return nil, err } - setQueryParams(req, callData.QueryParams) + setQueryParams(req, requestData.QueryParams) return req, nil } diff --git a/pkg/merchantorder/client.go b/pkg/merchantorder/client.go index a2715313..c7f41d7c 100644 --- a/pkg/merchantorder/client.go +++ b/pkg/merchantorder/client.go @@ -55,12 +55,12 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -71,12 +71,12 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { request.Check() - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ QueryParams: request.Filters, Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -89,13 +89,13 @@ func (c *client) Update(ctx context.Context, request UpdateRequest, id int64) (* "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -104,12 +104,12 @@ func (c *client) Update(ctx context.Context, request UpdateRequest, id int64) (* } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/oauth/client.go b/pkg/oauth/client.go index b11f288e..401c72c7 100644 --- a/pkg/oauth/client.go +++ b/pkg/oauth/client.go @@ -51,12 +51,12 @@ func (c *client) Create(ctx context.Context, authorizationCode, redirectURI stri GrantType: "authorization_code", } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -95,12 +95,12 @@ func (c *client) Refresh(ctx context.Context, refreshToken string) (*Response, e GrantType: "refresh_token", } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/payment/client.go b/pkg/payment/client.go index 8b6a7d7b..9f276ba5 100644 --- a/pkg/payment/client.go +++ b/pkg/payment/client.go @@ -58,12 +58,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -74,12 +74,12 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { request.Check() - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ QueryParams: request.Filters, Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -92,12 +92,12 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -112,13 +112,13 @@ func (c *client) Cancel(ctx context.Context, id int64) (*Response, error) { "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -133,13 +133,13 @@ func (c *client) Capture(ctx context.Context, id int64) (*Response, error) { "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -154,13 +154,13 @@ func (c *client) CaptureAmount(ctx context.Context, id int64, amount float64) (* "id": strconv.Itoa(int(id)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/paymentmethod/client.go b/pkg/paymentmethod/client.go index 769bb9d8..7792d027 100644 --- a/pkg/paymentmethod/client.go +++ b/pkg/paymentmethod/client.go @@ -29,11 +29,11 @@ func NewClient(cfg *config.Config) Client { } func (c *client) List(ctx context.Context) ([]Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) + result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/point/client.go b/pkg/point/client.go index e10fd9e7..95471e1e 100644 --- a/pkg/point/client.go +++ b/pkg/point/client.go @@ -61,13 +61,13 @@ func (c *client) Create(ctx context.Context, deviceID string, request CreateRequ "device_id": deviceID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPost, URL: urlPaymentIntent, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -80,12 +80,12 @@ func (c *client) Get(ctx context.Context, paymentIntentID string) (*Response, er "payment_intent_id": paymentIntentID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlPaymentIntentGet, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -99,12 +99,12 @@ func (c *client) Cancel(ctx context.Context, deviceID string, paymentIntentID st "payment_intent_id": paymentIntentID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodDelete, URL: urlPaymentIntentCancel, } - result, err := httpclient.Run[*CancelResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*CancelResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -113,11 +113,11 @@ func (c *client) Cancel(ctx context.Context, deviceID string, paymentIntentID st } func (c *client) ListDevices(ctx context.Context) (*DevicesResponse, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Method: http.MethodGet, URL: urlDevices, } - result, err := httpclient.Run[*DevicesResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*DevicesResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -130,13 +130,13 @@ func (c *client) UpdateDeviceOperatingMode(ctx context.Context, deviceID string, "device_id": deviceID, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPatch, URL: urlDevicesWithID, } - result, err := httpclient.Run[*OperatingModeResponse](ctx, c.cfg, callData) + result, err := httpclient.Run[*OperatingModeResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/preference/client.go b/pkg/preference/client.go index d911348e..d10fc79e 100644 --- a/pkg/preference/client.go +++ b/pkg/preference/client.go @@ -50,12 +50,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -68,12 +68,12 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { "id": id, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -86,13 +86,13 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo "id": id, } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -103,12 +103,12 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponsePage, error) { request.Check() - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[*SearchResponsePage](ctx, c.cfg, callData) + result, err := httpclient.Run[*SearchResponsePage](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/refund/client.go b/pkg/refund/client.go index 797d40a9..8515f0ca 100644 --- a/pkg/refund/client.go +++ b/pkg/refund/client.go @@ -55,12 +55,12 @@ func (c *client) Get(ctx context.Context, paymentID, refundID int64) (*Response, "refund_id": strconv.Itoa(int(refundID)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -73,12 +73,12 @@ func (c *client) List(ctx context.Context, paymentID int64) ([]Response, error) "id": strconv.Itoa(int(paymentID)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, callData) + result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -91,12 +91,12 @@ func (c *client) Create(ctx context.Context, paymentID int64) (*Response, error) "id": strconv.Itoa(int(paymentID)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ PathParams: pathParams, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -110,13 +110,13 @@ func (c *client) CreatePartialRefund(ctx context.Context, paymentID int64, amoun "id": strconv.Itoa(int(paymentID)), } - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Body: request, PathParams: pathParams, Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/user/client.go b/pkg/user/client.go index dc02d9a8..93a4984d 100644 --- a/pkg/user/client.go +++ b/pkg/user/client.go @@ -30,11 +30,11 @@ func NewClient(c *config.Config) Client { } func (c *client) Get(ctx context.Context) (*Response, error) { - callData := httpclient.CallData{ + requestData := httpclient.RequestData{ Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[*Response](ctx, c.cfg, callData) + result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } From d6421d920af42c2bd56355dc6e84cfa0e504fbbb Mon Sep 17 00:00:00 2001 From: gabs Date: Tue, 5 Mar 2024 11:12:34 -0300 Subject: [PATCH 14/19] Change marshal/unmarshal wrapper --- pkg/internal/httpclient/helper.go | 32 +++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go index ab7ea7af..b7dad2cb 100644 --- a/pkg/internal/httpclient/helper.go +++ b/pkg/internal/httpclient/helper.go @@ -49,11 +49,11 @@ func Run[T any](ctx context.Context, cfg *config.Config, requestData RequestData return result, err } - return wrapUnmarshal(b, result) + return unmarshal(b, result) } func createRequest(ctx context.Context, cfg *config.Config, requestData RequestData) (*http.Request, error) { - body, err := wrapMarshal(requestData.Body) + body, err := marshal(requestData.Body) if err != nil { return nil, err } @@ -72,19 +72,6 @@ func createRequest(ctx context.Context, cfg *config.Config, requestData RequestD return req, nil } -func wrapMarshal(body any) (io.Reader, error) { - if body == nil { - return nil, nil - } - - b, err := json.Marshal(&body) - if err != nil { - return nil, fmt.Errorf("error marshaling request body: %w", err) - } - - return strings.NewReader(string(b)), nil -} - func setHeaders(req *http.Request, cfg *config.Config) { req.Header.Set("X-Product-Id", productID) req.Header.Set("Accept", "application/json") @@ -151,7 +138,20 @@ func setQueryParams(req *http.Request, params map[string]string) { req.URL.RawQuery = queryParams.Encode() } -func wrapUnmarshal[T any](b []byte, response T) (T, error) { +func marshal(body any) (io.Reader, error) { + if body == nil { + return nil, nil + } + + b, err := json.Marshal(&body) + if err != nil { + return nil, fmt.Errorf("error marshaling request body: %w", err) + } + + return strings.NewReader(string(b)), nil +} + +func unmarshal[T any](b []byte, response T) (T, error) { if err := json.Unmarshal(b, &response); err != nil { return response, err } From 44b811e4dffe9138e792ba0994545ce3b0229efd Mon Sep 17 00:00:00 2001 From: gabs Date: Tue, 5 Mar 2024 11:12:52 -0300 Subject: [PATCH 15/19] Rename Check to SetDefaults --- pkg/customer/client.go | 2 +- pkg/customer/search_request.go | 4 ++-- pkg/merchantorder/client.go | 2 +- pkg/merchantorder/search_request.go | 4 ++-- pkg/payment/client.go | 2 +- pkg/payment/search_request.go | 4 ++-- pkg/preference/client.go | 2 +- pkg/preference/search_request.go | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pkg/customer/client.go b/pkg/customer/client.go index aa7edc06..93cc4c7f 100644 --- a/pkg/customer/client.go +++ b/pkg/customer/client.go @@ -64,7 +64,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - request.Check() + request.SetDefaults() requestData := httpclient.RequestData{ QueryParams: request.Filters, diff --git a/pkg/customer/search_request.go b/pkg/customer/search_request.go index 87b168a3..be70c7fc 100644 --- a/pkg/customer/search_request.go +++ b/pkg/customer/search_request.go @@ -12,8 +12,8 @@ type SearchRequest struct { Offset string } -// Check sets values for limit and offset when not sent. -func (s *SearchRequest) Check() { +// SetDefaults sets values for limit and offset when not sent. +func (s *SearchRequest) SetDefaults() { if len(s.Filters) == 0 { s.Filters = make(map[string]string, 2) } else { diff --git a/pkg/merchantorder/client.go b/pkg/merchantorder/client.go index c7f41d7c..086ad1b2 100644 --- a/pkg/merchantorder/client.go +++ b/pkg/merchantorder/client.go @@ -69,7 +69,7 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - request.Check() + request.SetDefaults() requestData := httpclient.RequestData{ QueryParams: request.Filters, diff --git a/pkg/merchantorder/search_request.go b/pkg/merchantorder/search_request.go index a2c7ec1e..22ec9b55 100644 --- a/pkg/merchantorder/search_request.go +++ b/pkg/merchantorder/search_request.go @@ -12,8 +12,8 @@ type SearchRequest struct { Offset string } -// Check sets values for limit and offset when not sent. -func (s *SearchRequest) Check() { +// SetDefaults sets values for limit and offset when not sent. +func (s *SearchRequest) SetDefaults() { if len(s.Filters) == 0 { s.Filters = make(map[string]string, 2) } else { diff --git a/pkg/payment/client.go b/pkg/payment/client.go index 9f276ba5..9bac98bf 100644 --- a/pkg/payment/client.go +++ b/pkg/payment/client.go @@ -72,7 +72,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - request.Check() + request.SetDefaults() requestData := httpclient.RequestData{ QueryParams: request.Filters, diff --git a/pkg/payment/search_request.go b/pkg/payment/search_request.go index 5f09d8c7..ef19a22c 100644 --- a/pkg/payment/search_request.go +++ b/pkg/payment/search_request.go @@ -12,8 +12,8 @@ type SearchRequest struct { Offset string } -// Check sets values for limit and offset when not sent. -func (s *SearchRequest) Check() { +// SetDefaults sets values for limit and offset when not sent. +func (s *SearchRequest) SetDefaults() { if len(s.Filters) == 0 { s.Filters = make(map[string]string, 2) } else { diff --git a/pkg/preference/client.go b/pkg/preference/client.go index d10fc79e..f2a733c8 100644 --- a/pkg/preference/client.go +++ b/pkg/preference/client.go @@ -101,7 +101,7 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponsePage, error) { - request.Check() + request.SetDefaults() requestData := httpclient.RequestData{ Body: request, diff --git a/pkg/preference/search_request.go b/pkg/preference/search_request.go index bb5da31f..ce7de3a6 100644 --- a/pkg/preference/search_request.go +++ b/pkg/preference/search_request.go @@ -10,7 +10,7 @@ type SearchRequest struct { Offset string } -func (s *SearchRequest) Check() { +func (s *SearchRequest) SetDefaults() { if len(s.Filters) == 0 { s.Filters = make(map[string]string, 2) } else { From 4853786277bdb627cab49f0fb59bd91f87c251e6 Mon Sep 17 00:00:00 2001 From: gabs Date: Tue, 5 Mar 2024 18:19:28 -0300 Subject: [PATCH 16/19] PR adjusts -> regex --- pkg/internal/httpclient/helper.go | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go index b7dad2cb..75e764b2 100644 --- a/pkg/internal/httpclient/helper.go +++ b/pkg/internal/httpclient/helper.go @@ -21,7 +21,7 @@ const ( ) var ( - pathParamFormat = regexp.MustCompile("[{}]") + pathParamRegexp = regexp.MustCompile(`{[^{}]*}`) userAgent = fmt.Sprintf("MercadoPago Go SDK/%s", currentSDKVersion) trackingID = fmt.Sprintf("platform:%s,type:SDK%s,so;", runtime.Version(), currentSDKVersion) @@ -97,35 +97,19 @@ func setPathParams(req *http.Request, params map[string]string) error { pathURL := req.URL.Path for k, v := range params { - pathParam := fmt.Sprintf("{%s}", k) + pathParam := "{" + k + "}" pathURL = strings.Replace(pathURL, pathParam, v, 1) } - if err := checkReplaces(pathURL); err != nil { - return err + matches := pathParamRegexp.FindAllString(pathURL, -1) + if matches != nil { + return fmt.Errorf("the following parameters weren't replaced: %v", matches) } req.URL.Path = pathURL return nil } -func checkReplaces(pathURL string) error { - if pathParamFormat.MatchString(pathURL) { - elements := strings.Split(pathURL, "/") - - notReplaced := []string{} - for _, e := range elements { - if pathParamFormat.MatchString(e) { - notReplaced = append(notReplaced, e) - } - } - - return fmt.Errorf("path parameters not informed: %s", strings.Join(notReplaced, ",")) - } - - return nil -} - func setQueryParams(req *http.Request, params map[string]string) { if len(params) == 0 { return From 18589c95e86bbb06343f75aebe41a59cdc05f0b3 Mon Sep 17 00:00:00 2001 From: gabs Date: Tue, 5 Mar 2024 18:44:30 -0300 Subject: [PATCH 17/19] Rename Run to DoRequest --- pkg/cardtoken/client.go | 2 +- pkg/customer/client.go | 8 ++++---- pkg/customercard/client.go | 10 +++++----- pkg/identificationtype/client.go | 2 +- pkg/internal/httpclient/helper.go | 2 +- pkg/merchantorder/client.go | 8 ++++---- pkg/oauth/client.go | 4 ++-- pkg/payment/client.go | 12 ++++++------ pkg/paymentmethod/client.go | 2 +- pkg/point/client.go | 10 +++++----- pkg/preference/client.go | 8 ++++---- pkg/refund/client.go | 8 ++++---- pkg/user/client.go | 2 +- 13 files changed, 39 insertions(+), 39 deletions(-) diff --git a/pkg/cardtoken/client.go b/pkg/cardtoken/client.go index 7dbc6dce..024e27fd 100644 --- a/pkg/cardtoken/client.go +++ b/pkg/cardtoken/client.go @@ -31,7 +31,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) Method: http.MethodPost, URL: url, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/customer/client.go b/pkg/customer/client.go index 93cc4c7f..bd7f5e03 100644 --- a/pkg/customer/client.go +++ b/pkg/customer/client.go @@ -55,7 +55,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -71,7 +71,7 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -89,7 +89,7 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -108,7 +108,7 @@ func (c *client) Update(ctx context.Context, id string, request Request) (*Respo Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/customercard/client.go b/pkg/customercard/client.go index 2567c74c..ea408ef2 100644 --- a/pkg/customercard/client.go +++ b/pkg/customercard/client.go @@ -64,7 +64,7 @@ func (c *client) Create(ctx context.Context, customerID string, request Request) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.config, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -83,7 +83,7 @@ func (c *client) Get(ctx context.Context, customerID, cardID string) (*Response, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -103,7 +103,7 @@ func (c *client) Update(ctx context.Context, customerID, cardID string, request Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -122,7 +122,7 @@ func (c *client) Delete(ctx context.Context, customerID, cardID string) (*Respon Method: http.MethodDelete, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.config, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.config, requestData) if err != nil { return nil, err } @@ -140,7 +140,7 @@ func (c *client) List(ctx context.Context, customerID string) ([]Response, error Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[[]Response](ctx, c.config, requestData) + result, err := httpclient.DoRequest[[]Response](ctx, c.config, requestData) if err != nil { return nil, err } diff --git a/pkg/identificationtype/client.go b/pkg/identificationtype/client.go index b0f560bc..98540b67 100644 --- a/pkg/identificationtype/client.go +++ b/pkg/identificationtype/client.go @@ -33,7 +33,7 @@ func (c *client) List(ctx context.Context) ([]Response, error) { Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/internal/httpclient/helper.go b/pkg/internal/httpclient/helper.go index 75e764b2..bf71ba43 100644 --- a/pkg/internal/httpclient/helper.go +++ b/pkg/internal/httpclient/helper.go @@ -36,7 +36,7 @@ type RequestData struct { URL string } -func Run[T any](ctx context.Context, cfg *config.Config, requestData RequestData) (T, error) { +func DoRequest[T any](ctx context.Context, cfg *config.Config, requestData RequestData) (T, error) { var result T req, err := createRequest(ctx, cfg, requestData) diff --git a/pkg/merchantorder/client.go b/pkg/merchantorder/client.go index 086ad1b2..ef489c87 100644 --- a/pkg/merchantorder/client.go +++ b/pkg/merchantorder/client.go @@ -60,7 +60,7 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -76,7 +76,7 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -95,7 +95,7 @@ func (c *client) Update(ctx context.Context, request UpdateRequest, id int64) (* Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -109,7 +109,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/oauth/client.go b/pkg/oauth/client.go index 401c72c7..e37190b9 100644 --- a/pkg/oauth/client.go +++ b/pkg/oauth/client.go @@ -56,7 +56,7 @@ func (c *client) Create(ctx context.Context, authorizationCode, redirectURI stri Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -100,7 +100,7 @@ func (c *client) Refresh(ctx context.Context, refreshToken string) (*Response, e Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/payment/client.go b/pkg/payment/client.go index 9bac98bf..b123963b 100644 --- a/pkg/payment/client.go +++ b/pkg/payment/client.go @@ -63,7 +63,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -79,7 +79,7 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp Method: http.MethodGet, URL: urlSearch, } - result, err := httpclient.Run[*SearchResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -97,7 +97,7 @@ func (c *client) Get(ctx context.Context, id int64) (*Response, error) { Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -118,7 +118,7 @@ func (c *client) Cancel(ctx context.Context, id int64) (*Response, error) { Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -139,7 +139,7 @@ func (c *client) Capture(ctx context.Context, id int64) (*Response, error) { Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -160,7 +160,7 @@ func (c *client) CaptureAmount(ctx context.Context, id int64, amount float64) (* Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/paymentmethod/client.go b/pkg/paymentmethod/client.go index 7792d027..296adf74 100644 --- a/pkg/paymentmethod/client.go +++ b/pkg/paymentmethod/client.go @@ -33,7 +33,7 @@ func (c *client) List(ctx context.Context) ([]Response, error) { Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/point/client.go b/pkg/point/client.go index 95471e1e..e28dd232 100644 --- a/pkg/point/client.go +++ b/pkg/point/client.go @@ -67,7 +67,7 @@ func (c *client) Create(ctx context.Context, deviceID string, request CreateRequ Method: http.MethodPost, URL: urlPaymentIntent, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -85,7 +85,7 @@ func (c *client) Get(ctx context.Context, paymentIntentID string) (*Response, er Method: http.MethodGet, URL: urlPaymentIntentGet, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -104,7 +104,7 @@ func (c *client) Cancel(ctx context.Context, deviceID string, paymentIntentID st Method: http.MethodDelete, URL: urlPaymentIntentCancel, } - result, err := httpclient.Run[*CancelResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*CancelResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -117,7 +117,7 @@ func (c *client) ListDevices(ctx context.Context) (*DevicesResponse, error) { Method: http.MethodGet, URL: urlDevices, } - result, err := httpclient.Run[*DevicesResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*DevicesResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -136,7 +136,7 @@ func (c *client) UpdateDeviceOperatingMode(ctx context.Context, deviceID string, Method: http.MethodPatch, URL: urlDevicesWithID, } - result, err := httpclient.Run[*OperatingModeResponse](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*OperatingModeResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/preference/client.go b/pkg/preference/client.go index f2a733c8..8d24ecf6 100644 --- a/pkg/preference/client.go +++ b/pkg/preference/client.go @@ -55,7 +55,7 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -73,7 +73,7 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -92,7 +92,7 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo Method: http.MethodPut, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -108,7 +108,7 @@ func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResp Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[*SearchResponsePage](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*SearchResponsePage](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/refund/client.go b/pkg/refund/client.go index 8515f0ca..78e4d614 100644 --- a/pkg/refund/client.go +++ b/pkg/refund/client.go @@ -60,7 +60,7 @@ func (c *client) Get(ctx context.Context, paymentID, refundID int64) (*Response, Method: http.MethodGet, URL: urlWithID, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -78,7 +78,7 @@ func (c *client) List(ctx context.Context, paymentID int64) ([]Response, error) Method: http.MethodGet, URL: urlBase, } - result, err := httpclient.Run[[]Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[[]Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -96,7 +96,7 @@ func (c *client) Create(ctx context.Context, paymentID int64) (*Response, error) Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -116,7 +116,7 @@ func (c *client) CreatePartialRefund(ctx context.Context, paymentID int64, amoun Method: http.MethodPost, URL: urlBase, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/user/client.go b/pkg/user/client.go index 93a4984d..629f0591 100644 --- a/pkg/user/client.go +++ b/pkg/user/client.go @@ -34,7 +34,7 @@ func (c *client) Get(ctx context.Context) (*Response, error) { Method: http.MethodGet, URL: url, } - result, err := httpclient.Run[*Response](ctx, c.cfg, requestData) + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } From ba64dd0f2f729223be88d5b0d16e701d29684f7b Mon Sep 17 00:00:00 2001 From: gabs Date: Wed, 6 Mar 2024 19:35:02 -0300 Subject: [PATCH 18/19] Refactor new clients --- pkg/invoice/client.go | 32 +++++++++-------- pkg/invoice/search_request.go | 26 +++++++------- pkg/preapprovalplan/client.go | 50 +++++++++++++++++++-------- pkg/preapprovalplan/search_request.go | 24 ++++++------- 4 files changed, 78 insertions(+), 54 deletions(-) diff --git a/pkg/invoice/client.go b/pkg/invoice/client.go index d19031b2..1ab9c699 100644 --- a/pkg/invoice/client.go +++ b/pkg/invoice/client.go @@ -2,10 +2,10 @@ package invoice import ( "context" - "fmt" + "net/http" + "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" - "net/url" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -40,31 +40,35 @@ func NewClient(c *config.Config) Client { } func (c *client) Get(ctx context.Context, id string) (*Response, error) { - params := map[string]string{ + pathParams := map[string]string{ "id": id, } - res, err := baseclient.Get[*Response](ctx, c.cfg, urlWithID, baseclient.WithPathParams(params)) + requestData := httpclient.RequestData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } - return res, nil + return result, nil } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - params := request.Parameters() + request.SetDefaults() - parsedURL, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing parseUrl: %w", err) + requestData := httpclient.RequestData{ + QueryParams: request.Filters, + Method: http.MethodGet, + URL: urlSearch, } - parsedURL.RawQuery = params - - res, err := baseclient.Get[*SearchResponse](ctx, c.cfg, parsedURL.String()) + result, err := httpclient.DoRequest[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } - return res, nil + return result, nil } diff --git a/pkg/invoice/search_request.go b/pkg/invoice/search_request.go index b3386471..79c2bacd 100644 --- a/pkg/invoice/search_request.go +++ b/pkg/invoice/search_request.go @@ -1,8 +1,6 @@ package invoice -import ( - "net/url" -) +import "strings" // SearchRequest contains filters accepted in search. type SearchRequest struct { @@ -12,12 +10,15 @@ type SearchRequest struct { Offset string } -// Parameters converts SearchRequest filters into a string of parameters of an HTTP request. -func (s SearchRequest) Parameters() string { - params := url.Values{} - - for k, v := range s.Filters { - params.Add(k, v) +// SetDefaults sets values for limit and offset when not sent. +func (s *SearchRequest) SetDefaults() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -25,16 +26,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } diff --git a/pkg/preapprovalplan/client.go b/pkg/preapprovalplan/client.go index 8ee65d68..0fe13e4b 100644 --- a/pkg/preapprovalplan/client.go +++ b/pkg/preapprovalplan/client.go @@ -2,11 +2,10 @@ package preapprovalplan import ( "context" - "fmt" + "net/http" + "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/baseclient" - "net/url" - "strings" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) const ( @@ -51,7 +50,12 @@ func NewClient(c *config.Config) Client { } func (c *client) Create(ctx context.Context, request Request) (*Response, error) { - result, err := baseclient.Post[*Response](ctx, c.cfg, urlBase, request) + requestData := httpclient.RequestData{ + Body: request, + Method: http.MethodPost, + URL: urlBase, + } + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -60,7 +64,16 @@ func (c *client) Create(ctx context.Context, request Request) (*Response, error) } func (c *client) Get(ctx context.Context, id string) (*Response, error) { - result, err := baseclient.Get[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", id, 1)) + pathParams := map[string]string{ + "id": id, + } + + requestData := httpclient.RequestData{ + PathParams: pathParams, + Method: http.MethodGet, + URL: urlWithID, + } + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -69,7 +82,17 @@ func (c *client) Get(ctx context.Context, id string) (*Response, error) { } func (c *client) Update(ctx context.Context, request Request, id string) (*Response, error) { - result, err := baseclient.Put[*Response](ctx, c.cfg, strings.Replace(urlWithID, "{id}", id, 1), request) + pathParams := map[string]string{ + "id": id, + } + + requestData := httpclient.RequestData{ + Body: request, + PathParams: pathParams, + Method: http.MethodPut, + URL: urlWithID, + } + result, err := httpclient.DoRequest[*Response](ctx, c.cfg, requestData) if err != nil { return nil, err } @@ -78,15 +101,14 @@ func (c *client) Update(ctx context.Context, request Request, id string) (*Respo } func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) { - params := request.Parameters() + request.SetDefaults() - parsedURL, err := url.Parse(urlSearch) - if err != nil { - return nil, fmt.Errorf("error parsing url: %w", err) + requestData := httpclient.RequestData{ + QueryParams: request.Filters, + Method: http.MethodGet, + URL: urlSearch, } - parsedURL.RawQuery = params - - result, err := baseclient.Get[*SearchResponse](ctx, c.cfg, parsedURL.String()) + result, err := httpclient.DoRequest[*SearchResponse](ctx, c.cfg, requestData) if err != nil { return nil, err } diff --git a/pkg/preapprovalplan/search_request.go b/pkg/preapprovalplan/search_request.go index e8134d60..310f6970 100644 --- a/pkg/preapprovalplan/search_request.go +++ b/pkg/preapprovalplan/search_request.go @@ -1,6 +1,6 @@ package preapprovalplan -import "net/url" +import "strings" // SearchRequest contains filters accepted in search. // Filters field can receive a lot of parameters. For details, see: @@ -12,12 +12,15 @@ type SearchRequest struct { Offset string } -// Parameters transforms SearchRequest into url params. -func (s SearchRequest) Parameters() string { - params := url.Values{} - - for k, v := range s.Filters { - params.Add(k, v) +// SetDefaults sets values for limit and offset when not sent. +func (s *SearchRequest) SetDefaults() { + if len(s.Filters) == 0 { + s.Filters = make(map[string]string, 2) + } else { + for k, v := range s.Filters { + delete(s.Filters, k) + s.Filters[strings.ToLower(k)] = v + } } if _, ok := s.Filters["limit"]; !ok { @@ -25,16 +28,13 @@ func (s SearchRequest) Parameters() string { if s.Limit != "" { limit = s.Limit } - params.Add("limit", limit) + s.Filters["limit"] = limit } - if _, ok := s.Filters["offset"]; !ok { offset := "0" if s.Offset != "" { offset = s.Offset } - params.Add("offset", offset) + s.Filters["offset"] = offset } - - return params.Encode() } From bbbf552e9158549f911b5b94da343eb14dd59dac Mon Sep 17 00:00:00 2001 From: gabs Date: Wed, 6 Mar 2024 19:48:08 -0300 Subject: [PATCH 19/19] Cover 100% from search request --- pkg/invoice/client_test.go | 12 +++++++++--- pkg/preapprovalplan/client_test.go | 12 +++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/pkg/invoice/client_test.go b/pkg/invoice/client_test.go index cf173c10..2b63cf28 100644 --- a/pkg/invoice/client_test.go +++ b/pkg/invoice/client_test.go @@ -3,8 +3,6 @@ package invoice import ( "context" "fmt" - "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/httpclient" "io" "net/http" "os" @@ -12,6 +10,10 @@ import ( "strings" "testing" "time" + + "github.com/google/uuid" + "github.com/mercadopago/sdk-go/pkg/config" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) var ( @@ -166,7 +168,11 @@ func TestSearch(t *testing.T) { args: args{ ctx: context.Background(), request: SearchRequest{ - Limit: "12", + Limit: "10", + Offset: "10", + Filters: map[string]string{ + "iD": uuid.NewString(), + }, }, }, want: &SearchResponse{ diff --git a/pkg/preapprovalplan/client_test.go b/pkg/preapprovalplan/client_test.go index e6851060..8e1ab691 100644 --- a/pkg/preapprovalplan/client_test.go +++ b/pkg/preapprovalplan/client_test.go @@ -3,8 +3,6 @@ package preapprovalplan import ( "context" "fmt" - "github.com/mercadopago/sdk-go/pkg/config" - "github.com/mercadopago/sdk-go/pkg/internal/httpclient" "io" "net/http" "os" @@ -12,6 +10,10 @@ import ( "strings" "testing" "time" + + "github.com/google/uuid" + "github.com/mercadopago/sdk-go/pkg/config" + "github.com/mercadopago/sdk-go/pkg/internal/httpclient" ) var ( @@ -397,7 +399,11 @@ func TestSearch(t *testing.T) { args: args{ ctx: context.Background(), request: SearchRequest{ - Limit: "10", + Limit: "10", + Offset: "10", + Filters: map[string]string{ + "iD": uuid.NewString(), + }, }, }, want: &SearchResponse{