-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathproducts.go
75 lines (59 loc) · 1.53 KB
/
products.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
package domain
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/aws-samples/serverless-go-demo/types"
)
var (
ErrJsonUnmarshal = errors.New("failed to parse product from request body")
ErrProductIdMismatch = errors.New("product ID in path does not match product ID in body")
)
type Products struct {
store types.Store
}
func NewProductsDomain(s types.Store) *Products {
return &Products{
store: s,
}
}
func (d *Products) GetProduct(ctx context.Context, id string) (*types.Product, error) {
product, err := d.store.Get(ctx, id)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return product, nil
}
func (d *Products) AllProducts(ctx context.Context, next *string) (types.ProductRange, error) {
if next != nil && strings.TrimSpace(*next) == "" {
next = nil
}
productRange, err := d.store.All(ctx, next)
if err != nil {
return productRange, fmt.Errorf("%w", err)
}
return productRange, nil
}
func (d *Products) PutProduct(ctx context.Context, id string, body []byte) (*types.Product, error) {
product := types.Product{}
if err := json.Unmarshal(body, &product); err != nil {
return nil, fmt.Errorf("%w", ErrJsonUnmarshal)
}
if product.Id != id {
return nil, fmt.Errorf("%w", ErrProductIdMismatch)
}
err := d.store.Put(ctx, product)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return &product, nil
}
func (d *Products) DeleteProduct(ctx context.Context, id string) error {
err := d.store.Delete(ctx, id)
if err != nil {
return fmt.Errorf("%w", err)
}
return nil
}