-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
89 lines (77 loc) · 2.04 KB
/
handler.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
package handler
import (
"context"
"io"
"time"
"github.com/focalsolution/micro-go-micro/errors"
"github.com/focalsolution/micro-go-micro/store"
pb "github.com/focalsolution/micro-go-micro/store/service/proto"
)
type Store struct {
Store store.Store
}
func (s *Store) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadResponse) error {
vals, err := s.Store.Read(req.Keys...)
if err != nil {
return errors.InternalServerError("go.micro.store", err.Error())
}
for _, val := range vals {
rsp.Records = append(rsp.Records, &pb.Record{
Key: val.Key,
Value: val.Value,
Expiry: int64(val.Expiry.Seconds()),
})
}
return nil
}
func (s *Store) Write(ctx context.Context, req *pb.WriteRequest, rsp *pb.WriteResponse) error {
records := make([]*store.Record, 0, len(req.Records))
for _, record := range req.Records {
records = append(records, &store.Record{
Key: record.Key,
Value: record.Value,
Expiry: time.Duration(record.Expiry) * time.Second,
})
}
err := s.Store.Write(records...)
if err != nil {
return errors.InternalServerError("go.micro.store", err.Error())
}
return nil
}
func (s *Store) Delete(ctx context.Context, req *pb.DeleteRequest, rsp *pb.DeleteResponse) error {
err := s.Store.Delete(req.Keys...)
if err != nil {
return errors.InternalServerError("go.micro.store", err.Error())
}
return nil
}
func (s *Store) List(ctx context.Context, req *pb.ListRequest, stream pb.Store_ListStream) error {
var vals []*store.Record
var err error
if len(req.Key) > 0 {
vals, err = s.Store.Read(req.Key)
} else {
vals, err = s.Store.List()
}
if err != nil {
return errors.InternalServerError("go.micro.store", err.Error())
}
rsp := new(pb.ListResponse)
// TODO: batch sync
for _, val := range vals {
rsp.Records = append(rsp.Records, &pb.Record{
Key: val.Key,
Value: val.Value,
Expiry: int64(val.Expiry.Seconds()),
})
}
err = stream.Send(rsp)
if err == io.EOF {
return nil
}
if err != nil {
return errors.InternalServerError("go.micro.store", err.Error())
}
return nil
}