Skip to content

Commit

Permalink
Merge pull request #10 from vseinstrumentiru/ctx
Browse files Browse the repository at this point in the history
ctx
  • Loading branch information
max107 authored May 18, 2022
2 parents bbe6181 + b6e7c3b commit c1d67c4
Show file tree
Hide file tree
Showing 26 changed files with 213 additions and 257 deletions.
2 changes: 1 addition & 1 deletion calculator-models.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type ServiceResp struct {

//GetCostReq Cost calculation on tariffs with priority request
type GetCostReq struct {
securableJSON
securable
Version *string `json:"version"`
SenderCityID *int `json:"senderCityId"`
ReceiverCityID *int `json:"receiverCityId"`
Expand Down
36 changes: 17 additions & 19 deletions calculator-service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,44 @@ package cdek

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/hashicorp/go-multierror"
"net/http"
)

//CalculateDelivery Cost calculation on tariffs with priority.
func (c Client) CalculateDelivery(req GetCostReq) (*GetCostRespResult, error) {
func (c Client) CalculateDelivery(ctx context.Context, req GetCostReq) (*GetCostRespResult, error) {
req.setAuth(c.auth)
reqByte, err := json.Marshal(req)

payload, err := json.Marshal(&req)
if err != nil {
return nil, err
}

resp, err := http.Post(c.calculatorURL, jsonContentType, bytes.NewReader(reqByte))
r, err := http.NewRequestWithContext(ctx, http.MethodPost, c.calculatorURL, bytes.NewReader(payload))
if err != nil {
return nil, err
}
r.Header.Add("Content-Type", jsonContentType)

defer func() {
_ = resp.Body.Close()
}()

body, _ := ioutil.ReadAll(resp.Body)

var getCostResp getCostResp
err = json.Unmarshal(body, &getCostResp)
resp, err := jsonReq[getCostResp](r)
if err != nil {
return nil, err
}

if getCostResp.ErrorResp != nil {
var errorMsg string
for _, err := range getCostResp.ErrorResp {
errorMsg += fmt.Sprintf("Error code: %s, error text: %s \n", *err.ErrorCode, *err.Msg)
if resp.ErrorResp != nil {
var errs error
for _, err := range resp.ErrorResp {
errs = multierror.Append(
errs,
fmt.Errorf("error code: %s, error text: %s", *err.ErrorCode, *err.Msg),
)
}

return nil, errors.New(errorMsg)
return nil, errs
}

return &getCostResp.Result, nil
return &resp.Result, nil
}
13 changes: 8 additions & 5 deletions calculator-service_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cdek

import (
"context"
"encoding/json"
"io/ioutil"
"math"
Expand All @@ -24,7 +25,7 @@ func calculateDeliveryGetMockServer() *httptest.Server {
Msg: strLink("Указанная вами версия API не поддерживается"),
})
}
if *getCostReq.Secure == "" || *getCostReq.AuthLogin == "" || *getCostReq.DateExecute == "" {
if *getCostReq.Secure == "" || *getCostReq.Account == "" || *getCostReq.Date == "" {
errorsResp = append(errorsResp, Error{
ErrorCode: strLink("2"),
Msg: strLink("Ошибка авторизации"),
Expand Down Expand Up @@ -191,12 +192,12 @@ func TestClient_CalculateDelivery(t *testing.T) {
SenderCityID: nil,
ReceiverCityID: intLink(2),
TariffID: intLink(3),
Goods: []*Good{
Goods: []*Good{
{
Weight: math.Inf(1),
},
},
Services: nil,
Services: nil,
},
},
nil,
Expand All @@ -214,10 +215,11 @@ func TestClient_CalculateDelivery(t *testing.T) {
true,
},
}
ctx := context.TODO()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := tt.args.client
got, err := cl.CalculateDelivery(tt.args.req)
got, err := cl.CalculateDelivery(ctx, tt.args.req)
if (err != nil) != tt.wantErr {
t.Errorf("CalculateDelivery() error = %v, wantErr %v", err, tt.wantErr)
return
Expand All @@ -233,7 +235,8 @@ func ExampleClient_CalculateDelivery() {
client := NewClient("https://integration.edu.cdek.ru/")
client.SetAuth("z9GRRu7FxmO53CQ9cFfI6qiy32wpfTkd", "w24JTCv4MnAcuRTx0oHjHLDtyt3I6IBq")

result, err := client.CalculateDelivery(*NewGetCostReq(61208, 2108, 10))
ctx := context.TODO()
result, err := client.CalculateDelivery(ctx, *NewGetCostReq(61208, 2108, 10))

_, _ = result, err
}
47 changes: 9 additions & 38 deletions city-service.go
Original file line number Diff line number Diff line change
@@ -1,63 +1,34 @@
package cdek

import (
"encoding/json"
"io/ioutil"
"context"
"net/http"
"net/url"
"path"

"github.com/hashicorp/go-multierror"
)

const (
citiesURL = "v1/location/cities/json"
)

//GetCities This method is used to load detailed information on cities.
func (c Client) GetCities(filter map[CityFilter]string) (*GetCitiesResp, error) {
func (c Client) GetCities(ctx context.Context, filter map[CityFilter]string) (*GetCitiesResp, error) {
serverURL, err := url.Parse(c.apiURL)
if err != nil {
return nil, err
}

serverURL.Path = path.Join(serverURL.Path, citiesURL)

queryString := serverURL.Query()
for filterKey, value := range filter {
queryString.Set(string(filterKey), value)
qs := serverURL.Query()
for k, v := range filter {
qs.Set(string(k), v)
}
serverURL.RawQuery = queryString.Encode()

reqURL := serverURL.String()
serverURL.Path = path.Join(serverURL.Path, citiesURL)
serverURL.RawQuery = qs.Encode()

resp, err := http.Get(reqURL)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, serverURL.String(), nil)
if err != nil {
return nil, err
}

defer func() {
_ = resp.Body.Close()
}()

body, _ := ioutil.ReadAll(resp.Body)

var cities GetCitiesResp
err = json.Unmarshal(body, &cities)
if err != nil {
var alertResponse AlertResponse
err = json.Unmarshal(body, &alertResponse)
if err != nil {
return nil, err
}

multiError := &multierror.Error{}
for _, alert := range alertResponse.Alerts {
multiError = multierror.Append(alert)
}

return nil, multiError.ErrorOrNil()
}

return &cities, nil
return jsonReq[GetCitiesResp](req)
}
7 changes: 5 additions & 2 deletions city-service_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cdek

import (
"context"
"net/http"
"net/http/httptest"
"reflect"
Expand Down Expand Up @@ -178,10 +179,11 @@ func TestClient_GetCities(t *testing.T) {
wantErr: true,
},
}
ctx := context.TODO()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := tt.args.client
got, err := cl.GetCities(tt.args.filter)
got, err := cl.GetCities(ctx, tt.args.filter)
if (err != nil) != tt.wantErr {
t.Errorf("GetCities() error = %v, wantErr %v", err, tt.wantErr)
return
Expand All @@ -197,7 +199,8 @@ func ExampleClient_GetCities() {
client := NewClient("https://integration.edu.cdek.ru/")
client.SetAuth("z9GRRu7FxmO53CQ9cFfI6qiy32wpfTkd", "w24JTCv4MnAcuRTx0oHjHLDtyt3I6IBq")

result, err := client.GetCities(map[CityFilter]string{
ctx := context.TODO()
result, err := client.GetCities(ctx, map[CityFilter]string{
CityFilterPage: "3",
})

Expand Down
17 changes: 9 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cdek

import (
"context"
"crypto/md5"
"encoding/hex"
"time"
Expand All @@ -23,14 +24,14 @@ type ServiceAccessСonfigurator interface {
type ServiceProvider interface {
ServiceAccessСonfigurator

CalculateDelivery(req GetCostReq) (*GetCostRespResult, error)
GetCities(filter map[CityFilter]string) (*GetCitiesResp, error)
GetPvzList(filter map[PvzListFilter]string) ([]*Pvz, error)
GetRegions(filter map[RegionFilter]string) (*GetRegionsResp, error)
RegisterOrder(req RegisterOrderReq) (*RegisterOrderResp, error)
UpdateOrder(req UpdateOrderReq) (*UpdateOrderResp, error)
DeleteOrder(req DeleteOrderReq) (*DeleteOrderResp, error)
GetStatusReport(statusReportReq StatusReport) (*StatusReportResp, error)
CalculateDelivery(ctx context.Context, req GetCostReq) (*GetCostRespResult, error)
GetCities(ctx context.Context, filter map[CityFilter]string) (*GetCitiesResp, error)
GetPvzList(ctx context.Context, filter map[PvzListFilter]string) ([]*Pvz, error)
GetRegions(ctx context.Context, filter map[RegionFilter]string) (*GetRegionsResp, error)
RegisterOrder(ctx context.Context, req RegisterOrderReq) (*RegisterOrderResp, error)
UpdateOrder(ctx context.Context, req UpdateOrderReq) (*UpdateOrderResp, error)
DeleteOrder(ctx context.Context, req DeleteOrderReq) (*DeleteOrderResp, error)
GetStatusReport(ctx context.Context, statusReportReq StatusReport) (*StatusReportResp, error)
}

//Client SDK Client configuration
Expand Down
2 changes: 1 addition & 1 deletion delete-order-models.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "encoding/xml"

//DeleteOrderReq request structure for deleting order from CDEK
type DeleteOrderReq struct {
securableXML
securable
XMLName xml.Name `xml:"DeleteRequest"`
Number *string `xml:"Number,attr"`
OrderCount *int `xml:"OrderCount,attr"`
Expand Down
43 changes: 18 additions & 25 deletions delete-order-service.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package cdek

import (
"context"
"encoding/xml"
"io/ioutil"
"net/http"
"net/url"
"path"
Expand All @@ -16,51 +16,44 @@ const (
)

//DeleteOrder The method is designed to cancel/delete an order at the client's initiative.
func (c Client) DeleteOrder(req DeleteOrderReq) (*DeleteOrderResp, error) {
req.setAuth(c.auth)
reqByte, err := xml.Marshal(req)

func (c Client) DeleteOrder(ctx context.Context, req DeleteOrderReq) (*DeleteOrderResp, error) {
serverURL, err := url.Parse(c.apiURL)
if err != nil {
return nil, err
}
serverURL.Path = path.Join(serverURL.Path, deleteOrderURL)

data := make(url.Values)
data.Add("xml_request", string(reqByte))
req.setAuth(c.auth)

serverURL, err := url.Parse(c.apiURL)
xmlBytes, err := xml.Marshal(req)
if err != nil {
return nil, err
}

serverURL.Path = path.Join(serverURL.Path, deleteOrderURL)
reqURL := serverURL.String()
data := &url.Values{}
data.Add("xml_request", string(xmlBytes))

resp, err := http.Post(reqURL, urlFormEncoded, strings.NewReader(data.Encode()))
r, err := http.NewRequestWithContext(ctx, http.MethodPost, serverURL.String(), strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
r.Header.Add("Content-Type", urlFormEncoded)

defer func() {
_ = resp.Body.Close()
}()

body, _ := ioutil.ReadAll(resp.Body)

var deleteOrderResp DeleteOrderResp
err = xml.Unmarshal(body, &deleteOrderResp)
resp, err := xmlReq[DeleteOrderResp](r)
if err != nil {
return nil, err
}

multiError := &multierror.Error{}
for _, o := range deleteOrderResp.Order {
var errs error
for _, o := range resp.Order {
if o.IsErroneous() {
multiError = multierror.Append(o.GetError())
errs = multierror.Append(errs, o.GetError())
}
}
if multiError.Len() > 0 {
return nil, multiError.ErrorOrNil()

if errs != nil {
return nil, errs
}

return &deleteOrderResp, nil
return resp, nil
}
7 changes: 5 additions & 2 deletions delete-order-service_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cdek

import (
"context"
"encoding/json"
"encoding/xml"
"net/http"
Expand Down Expand Up @@ -187,10 +188,11 @@ func TestClient_DeleteOrder(t *testing.T) {
wantErr: true,
},
}
ctx := context.TODO()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := tt.fields.client
got, err := cl.DeleteOrder(tt.args.req)
got, err := cl.DeleteOrder(ctx, tt.args.req)
if (err != nil) != tt.wantErr {
t.Errorf("DeleteOrder() error = %v, wantErr %v", err, tt.wantErr)
return
Expand All @@ -208,7 +210,8 @@ func ExampleClient_DeleteOrder() {
client := NewClient("https://integration.edu.cdek.ru/")
client.SetAuth("z9GRRu7FxmO53CQ9cFfI6qiy32wpfTkd", "w24JTCv4MnAcuRTx0oHjHLDtyt3I6IBq")

result, err := client.DeleteOrder(*NewDeleteOrderReq(
ctx := context.TODO()
result, err := client.DeleteOrder(ctx, *NewDeleteOrderReq(
"number-soOEl0",
1,
*NewDeleteOrder().SetNumber("number-soOEl0"),
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module github.com/vseinstrumentiru/cdek

go 1.12
go 1.18

require github.com/hashicorp/go-multierror v1.0.0

require github.com/hashicorp/errwrap v1.0.0 // indirect
Loading

0 comments on commit c1d67c4

Please sign in to comment.