/
product.go
130 lines (95 loc) · 2.58 KB
/
product.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package data
import (
"context"
"errors"
"fmt"
"github.com/thetnaingtn/go-boutique/app/product/internal/biz"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/uuid"
)
var (
ErrProductNotFound = errors.New("product not found")
)
type productRepo struct {
data *Data
log *log.Helper
}
// NewProductRepo .
func NewProductRepo(data *Data, logger log.Logger) biz.ProductRepo {
return &productRepo{
data: data,
log: log.NewHelper(logger),
}
}
func (r *productRepo) Save(ctx context.Context, g *biz.Product) (*biz.Product, error) {
id := uuid.New()
product := &biz.Product{
Id: id.String(),
Name: g.Name,
Description: g.Description,
Price: g.Price,
}
tx := r.data.db.MustBegin()
if _, err := tx.NamedExec(`INSERT INTO products (id,name,description,price) VALUES (:id,:name,:description,:price)`, product); err != nil {
return &biz.Product{}, err
}
tx.Commit()
return product, nil
}
func (r *productRepo) Update(ctx context.Context, id string, p *biz.UpdateProduct) (*biz.Product, error) {
product, err := r.FindByID(ctx, id)
if err != nil {
return &biz.Product{}, err
}
if p.Name != nil {
product.Name = *p.Name
}
if p.Description != nil {
product.Description = *p.Description
}
if p.Price != nil {
product.Price = *p.Price
}
q := `UPDATE products SET "name" = :name, "description" = :description, "price" = :price WHERE "id" = :id`
_, err = r.data.db.NamedExecContext(ctx, q, product)
if err != nil {
return &biz.Product{}, err
}
return product, nil
}
func (r *productRepo) FindByID(ctx context.Context, id string) (*biz.Product, error) {
var product biz.Product
data := struct {
Id string `db:"id"`
}{Id: id}
row, _ := r.data.db.NamedQueryContext(ctx, `SELECT * FROM products WHERE id = :id`, data)
if !row.Next() {
return &biz.Product{}, ErrProductNotFound
}
if err := row.StructScan(&product); err != nil {
return &biz.Product{}, fmt.Errorf("error when getting user by id: %w", err)
}
return &product, nil
}
func (r *productRepo) DeleteById(ctx context.Context, id string) (string, error) {
product, err := r.FindByID(ctx, id)
if err != nil {
return "", err
}
if product == nil {
return "", ErrProductNotFound
}
q := `DELETE FROM products WHERE id = :id`
data := struct{ Id string }{Id: id}
_, err = r.data.db.NamedExecContext(ctx, q, data)
if err != nil {
return "", err
}
return id, nil
}
func (r *productRepo) ListByHello(context.Context, string) ([]*biz.Product, error) {
return nil, nil
}
func (r *productRepo) ListAll(context.Context) ([]*biz.Product, error) {
return nil, nil
}