/
product_ctl_services.go
67 lines (57 loc) · 1.41 KB
/
product_ctl_services.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 services
import (
"context"
"encoding/json"
"io"
"net/http"
"strconv"
"github.com/kumin/go-tpc/services/customer_service/entities"
"github.com/kumin/go-tpc/services/customer_service/repos"
"github.com/kumin/go-tpc/services/customer_service/repos/mysql"
)
type ProductCtlServices struct {
repo repos.ProductRepo
}
func NewProductCtlServices(
repo *mysql.ProductMysqlRepo,
) *ProductCtlServices {
return &ProductCtlServices{
repo: repo,
}
}
func (p *ProductCtlServices) AddProduct(
ctx context.Context,
req *http.Request,
) (*entities.Product, error) {
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
var prod *entities.Product
if err := json.Unmarshal(body, &prod); err != nil {
return nil, err
}
return p.repo.AddProduct(ctx, prod)
}
func (p *ProductCtlServices) GetProduct(
ctx context.Context,
req *http.Request,
) (*entities.Product, error) {
id, err := strconv.ParseInt(req.URL.Query().Get("id"), 10, 64)
if err != nil {
return nil, entities.ParamInvalid
}
return p.repo.GetProduct(ctx, id)
}
func (p *ProductCtlServices) ListProducts(
ctx context.Context,
req *http.Request,
) ([]*entities.Product, error) {
page, err1 := strconv.Atoi(req.URL.Query().Get("page"))
limit, err2 := strconv.Atoi(req.URL.Query().Get("limit"))
if err1 != nil || err2 != nil {
return nil, entities.ParamInvalid
}
return p.repo.ListProducts(ctx, page, limit)
}