forked from tinrab/spidey
/
client.go
102 lines (90 loc) · 2.14 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package order
import (
"context"
"log"
"time"
"github.com/kaansari/spidey/order/pb"
"google.golang.org/grpc"
)
type Client struct {
conn *grpc.ClientConn
service pb.OrderServiceClient
}
func NewClient(url string) (*Client, error) {
conn, err := grpc.Dial(url, grpc.WithInsecure())
if err != nil {
return nil, err
}
c := pb.NewOrderServiceClient(conn)
return &Client{conn, c}, nil
}
func (c *Client) Close() {
c.conn.Close()
}
func (c *Client) PostOrder(
ctx context.Context,
accountID string,
products []OrderedProduct,
) (*Order, error) {
protoProducts := []*pb.PostOrderRequest_OrderProduct{}
for _, p := range products {
protoProducts = append(protoProducts, &pb.PostOrderRequest_OrderProduct{
ProductId: p.ID,
Quantity: p.Quantity,
})
}
r, err := c.service.PostOrder(
ctx,
&pb.PostOrderRequest{
AccountId: accountID,
Products: protoProducts,
},
)
if err != nil {
return nil, err
}
// Create response order
newOrder := r.Order
newOrderCreatedAt := time.Time{}
newOrderCreatedAt.UnmarshalBinary(newOrder.CreatedAt)
return &Order{
ID: newOrder.Id,
CreatedAt: newOrderCreatedAt,
TotalPrice: newOrder.TotalPrice,
AccountID: newOrder.AccountId,
Products: products,
}, nil
}
func (c *Client) GetOrdersForAccount(ctx context.Context, accountID string) ([]Order, error) {
r, err := c.service.GetOrdersForAccount(ctx, &pb.GetOrdersForAccountRequest{
AccountId: accountID,
})
if err != nil {
log.Println(err)
return nil, err
}
// Create response orders
orders := []Order{}
for _, orderProto := range r.Orders {
newOrder := Order{
ID: orderProto.Id,
TotalPrice: orderProto.TotalPrice,
AccountID: orderProto.AccountId,
}
newOrder.CreatedAt = time.Time{}
newOrder.CreatedAt.UnmarshalBinary(orderProto.CreatedAt)
products := []OrderedProduct{}
for _, p := range orderProto.Products {
products = append(products, OrderedProduct{
ID: p.Id,
Quantity: p.Quantity,
Name: p.Name,
Description: p.Description,
Price: p.Price,
})
}
newOrder.Products = products
orders = append(orders, newOrder)
}
return orders, nil
}