-
Notifications
You must be signed in to change notification settings - Fork 1k
/
store.go
83 lines (69 loc) · 1.8 KB
/
store.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 client
import (
pb "github.com/micro/micro/v3/proto/events"
"github.com/micro/micro/v3/service/client"
"github.com/micro/micro/v3/service/context"
"github.com/micro/micro/v3/service/events"
"github.com/micro/micro/v3/service/events/util"
)
// NewStore returns an initialized store handler
func NewStore() events.Store {
return new(store)
}
type store struct {
Client pb.StoreService
}
func (s *store) Read(topic string, opts ...events.ReadOption) ([]*events.Event, error) {
// parse the options
var options events.ReadOptions
for _, o := range opts {
o(&options)
}
req := &pb.ReadRequest{
Topic: topic,
}
if options.Limit > 0 {
req.Limit = uint64(options.Limit)
}
if options.Offset > 0 {
req.Offset = uint64(options.Offset)
}
// execute the RPC
rsp, err := s.client().Read(context.DefaultContext, req, client.WithAuthToken())
if err != nil {
return nil, err
}
// serialize the response
result := make([]*events.Event, len(rsp.Events))
for i, r := range rsp.Events {
ev := util.DeserializeEvent(r)
result[i] = &ev
}
return result, nil
}
func (s *store) Write(ev *events.Event, opts ...events.WriteOption) error {
// parse options
var options events.WriteOptions
for _, o := range opts {
o(&options)
}
// start the stream
_, err := s.client().Write(context.DefaultContext, &pb.WriteRequest{
Event: &pb.Event{
Id: ev.ID,
Topic: ev.Topic,
Metadata: ev.Metadata,
Payload: ev.Payload,
Timestamp: ev.Timestamp.Unix(),
},
}, client.WithAuthToken())
return err
}
// this is a tmp solution since the client isn't initialized when NewStream is called. There is a
// fix in the works in another PR.
func (s *store) client() pb.StoreService {
if s.Client == nil {
s.Client = pb.NewStoreService("events", client.DefaultClient)
}
return s.Client
}