forked from hiscaler/woocommerce-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shipping_zone.go
99 lines (80 loc) · 2.26 KB
/
shipping_zone.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package woocommerce
import (
"fmt"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hiscaler/woocommerce-go/entity"
jsoniter "github.com/json-iterator/go"
)
type shippingZoneService service
// All list all shipping zones
func (s shippingZoneService) All() (items []entity.ShippingZone, err error) {
resp, err := s.httpClient.R().Get("/shipping/zones")
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &items)
}
return
}
// One retrieve a shipping zone
func (s shippingZoneService) One(id int) (item entity.ShippingZone, err error) {
resp, err := s.httpClient.R().Get(fmt.Sprintf("/shipping/zones/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
}
return
}
// Create
type CreateShippingZoneRequest struct {
Name string `json:"name"`
Order int `json:"order"`
}
func (m CreateShippingZoneRequest) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Name, validation.Required.Error("名称不能为空")),
validation.Field(&m.Order, validation.Min(0).Error("排序值不能小于 {{.threshold}}")),
)
}
func (s shippingZoneService) Create(req CreateShippingZoneRequest) (item entity.ShippingZone, err error) {
if err = req.Validate(); err != nil {
return
}
resp, err := s.httpClient.R().SetBody(req).Post("/shipping/zones")
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
}
return
}
// Update
type UpdateShippingZoneRequest = CreateShippingZoneRequest
func (s shippingZoneService) Update(id int, req UpdateShippingZoneRequest) (item entity.ShippingZone, err error) {
if err = req.Validate(); err != nil {
return
}
resp, err := s.httpClient.R().SetBody(req).Put(fmt.Sprintf("/shipping/zones/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
}
return
}
// Delete delete a shipping zone
func (s shippingZoneService) Delete(id int, force bool) (item entity.ShippingZone, err error) {
resp, err := s.httpClient.R().SetBody(map[string]bool{"force": force}).Delete(fmt.Sprintf("/shipping/zones/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
}
return
}