/
cart.go
67 lines (56 loc) · 1.53 KB
/
cart.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
package biz
import (
"context"
"github.com/go-kratos/kratos/v2/log"
)
// Cart is a Cart model.
type Cart struct {
UserId string `json:"user_id"`
Items []CartItem `json:"items,omitempty"`
}
type CartItem struct {
ProductId string `json:"product_id"`
Quantity int32 `json:"quantity"`
}
// CartRepo is a Cart repo.
type CartRepo interface {
Empty(context.Context, string) error
AddItem(context.Context, string, *CartItem) error
Get(context.Context, string) (*Cart, error)
}
// CartUsecase is a Cart usecase.
type CartUsecase struct {
repo CartRepo
log *log.Helper
}
// NewCartUsecase new a Cart usecase.
func NewCartUsecase(repo CartRepo, logger log.Logger) *CartUsecase {
return &CartUsecase{repo: repo, log: log.NewHelper(logger)}
}
// AddItem add cart item into a cart for a user.
func (uc *CartUsecase) AddItem(ctx context.Context, userId string, item *CartItem) error {
err := uc.repo.AddItem(ctx, userId, item)
if err != nil {
return err
}
uc.log.WithContext(ctx).Infof("AddItem: %v", *item)
return nil
}
// GetCart get cart of a user.
func (uc *CartUsecase) GetCart(ctx context.Context, userId string) (*Cart, error) {
cart, err := uc.repo.Get(ctx, userId)
if err != nil {
return nil, err
}
uc.log.WithContext(ctx).Infof("GetCart: %s", userId)
return cart, nil
}
// EmptyCart clear all items in a cart.
func (uc *CartUsecase) Empty(ctx context.Context, userId string) error {
err := uc.repo.Empty(ctx, userId)
if err != nil {
return err
}
uc.log.WithContext(ctx).Infof("EmptyCart: %s", userId)
return nil
}