/
client.go
90 lines (81 loc) · 1.75 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package catalog
import (
"context"
"github.com/tinrab/spidey/catalog/pb"
"google.golang.org/grpc"
)
type Client struct {
conn *grpc.ClientConn
service pb.CatalogServiceClient
}
func NewClient(url string) (*Client, error) {
conn, err := grpc.Dial(url, grpc.WithInsecure())
if err != nil {
return nil, err
}
c := pb.NewCatalogServiceClient(conn)
return &Client{conn, c}, nil
}
func (c *Client) Close() {
c.conn.Close()
}
func (c *Client) PostProduct(ctx context.Context, name, description string, price float64) (*Product, error) {
r, err := c.service.PostProduct(
ctx,
&pb.PostProductRequest{
Name: name,
Description: description,
Price: price,
},
)
if err != nil {
return nil, err
}
return &Product{
ID: r.Product.Id,
Name: r.Product.Name,
Description: r.Product.Description,
Price: r.Product.Price,
}, nil
}
func (c *Client) GetProduct(ctx context.Context, id string) (*Product, error) {
r, err := c.service.GetProduct(
ctx,
&pb.GetProductRequest{
Id: id,
},
)
if err != nil {
return nil, err
}
return &Product{
ID: r.Product.Id,
Name: r.Product.Name,
Description: r.Product.Description,
Price: r.Product.Price,
}, nil
}
func (c *Client) GetProducts(ctx context.Context, skip uint64, take uint64, ids []string, query string) ([]Product, error) {
r, err := c.service.GetProducts(
ctx,
&pb.GetProductsRequest{
Ids: ids,
Skip: skip,
Take: take,
Query: query,
},
)
if err != nil {
return nil, err
}
products := []Product{}
for _, p := range r.Products {
products = append(products, Product{
ID: p.Id,
Name: p.Name,
Description: p.Description,
Price: p.Price,
})
}
return products, nil
}