github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/events/client/store.go (about) 1 package client 2 3 import ( 4 pb "github.com/tickoalcantara12/micro/v3/proto/events" 5 "github.com/tickoalcantara12/micro/v3/service/client" 6 "github.com/tickoalcantara12/micro/v3/service/context" 7 "github.com/tickoalcantara12/micro/v3/service/events" 8 "github.com/tickoalcantara12/micro/v3/service/events/util" 9 ) 10 11 // NewStore returns an initialized store handler 12 func NewStore() events.Store { 13 return new(store) 14 } 15 16 type store struct { 17 Client pb.StoreService 18 } 19 20 func (s *store) Read(topic string, opts ...events.ReadOption) ([]*events.Event, error) { 21 // parse the options 22 var options events.ReadOptions 23 for _, o := range opts { 24 o(&options) 25 } 26 27 req := &pb.ReadRequest{ 28 Topic: topic, 29 } 30 31 if options.Limit > 0 { 32 req.Limit = uint64(options.Limit) 33 } 34 35 if options.Offset > 0 { 36 req.Offset = uint64(options.Offset) 37 } 38 39 // execute the RPC 40 rsp, err := s.client().Read(context.DefaultContext, req, client.WithAuthToken()) 41 if err != nil { 42 return nil, err 43 } 44 45 // serialize the response 46 result := make([]*events.Event, len(rsp.Events)) 47 for i, r := range rsp.Events { 48 ev := util.DeserializeEvent(r) 49 result[i] = &ev 50 } 51 52 return result, nil 53 } 54 55 func (s *store) Write(ev *events.Event, opts ...events.WriteOption) error { 56 // parse options 57 var options events.WriteOptions 58 for _, o := range opts { 59 o(&options) 60 } 61 62 // start the stream 63 _, err := s.client().Write(context.DefaultContext, &pb.WriteRequest{ 64 Event: &pb.Event{ 65 Id: ev.ID, 66 Topic: ev.Topic, 67 Metadata: ev.Metadata, 68 Payload: ev.Payload, 69 Timestamp: ev.Timestamp.Unix(), 70 }, 71 }, client.WithAuthToken()) 72 73 return err 74 } 75 76 // this is a tmp solution since the client isn't initialized when NewStream is called. There is a 77 // fix in the works in another PR. 78 func (s *store) client() pb.StoreService { 79 if s.Client == nil { 80 s.Client = pb.NewStoreService("events", client.DefaultClient) 81 } 82 return s.Client 83 }