-
Notifications
You must be signed in to change notification settings - Fork 0
/
item.go
83 lines (65 loc) · 1.98 KB
/
item.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
package redis
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
gerrors "github.com/elojah/game_02/pkg/errors"
"github.com/elojah/game_02/pkg/item"
)
const (
itemKey = "item:"
)
// Upsert implementation for item in redis.
func (s *Store) Upsert(ctx context.Context, i item.I) error {
raw, err := i.Marshal()
if err != nil {
return err
}
if err := s.Set(ctx, itemKey+i.ID.String(), raw, 0).Err(); err != nil {
return fmt.Errorf("upsert item %s: %w", i.ID.String(), err)
}
return nil
}
// Fetch implementation for item in redis.
func (s *Store) Fetch(ctx context.Context, filter item.Filter) (item.I, error) {
val, err := s.Get(ctx, itemKey+filter.ID.String()).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
return item.I{}, fmt.Errorf("fetch item %s: %w", filter.ID.String(), err)
}
return item.I{}, fmt.Errorf(
"fetch item %s: %w",
filter.ID.String(),
gerrors.ErrNotFound{Resource: itemKey, Index: filter.ID.String() + ":" + filter.ID.String()},
)
}
var i item.I
if err := i.Unmarshal([]byte(val)); err != nil {
return item.I{}, fmt.Errorf("fetch item %s: %w", filter.ID.String(), err)
}
return i, nil
}
// FetchMany implementation for item in redis.
func (s *Store) FetchMany(ctx context.Context, filter item.Filter) (map[string]item.I, error) {
is := make(map[string]item.I, len(filter.IDs))
for _, id := range filter.IDs {
val, err := s.Get(ctx, itemKey+id.String()).Result()
if err != nil {
return nil, fmt.Errorf("fetch item %s: %w", id.String(), err)
}
var tmp item.I
if err := tmp.Unmarshal([]byte(val)); err != nil {
return nil, fmt.Errorf("fetch items %s: %w", filter.ID.String(), err)
}
is[tmp.ID.String()] = tmp
}
return is, nil
}
// Delete implementation for item in redis.
func (s *Store) Delete(ctx context.Context, filter item.Filter) error {
if err := s.Del(ctx, itemKey+filter.ID.String()).Err(); err != nil {
return fmt.Errorf("remove item %s: %w", filter.ID.String(), err)
}
return nil
}