Skip to content

Commit

Permalink
dstore/events: Increment
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel committed Mar 31, 2021
1 parent 917b5fe commit 0b24b65
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
25 changes: 25 additions & 0 deletions dstore/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,31 @@ func (m *Mem) EventsAdd(ctx context.Context, path string, data [][]byte) ([]*eve
return out, idx, nil
}

func (m *Mem) Increment(ctx context.Context, path string, name string, n int64) (int64, error) {
doc, err := m.Get(ctx, path)
if err != nil {
return 0, err
}
val := int64(0)
if doc != nil {
v, ok := doc.Get(name)
if err != nil {
return 0, err
}
if !ok {
val = int64(0)
} else {
val = v.(int64)
}
}

next := val + n
if err := m.Set(ctx, path, map[string]interface{}{name: next}, MergeAll()); err != nil {
return 0, err
}
return next, nil
}

// EventPositions returns positions for event logs at the specified paths.
func (m *Mem) EventPositions(ctx context.Context, paths []string) (map[string]*events.Position, error) {
positions := map[string]*events.Position{}
Expand Down
3 changes: 3 additions & 0 deletions dstore/events/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ type Events interface {

// EventPositions returns current positions of event logs at the specified paths.
EventPositions(ctx context.Context, paths []string) (map[string]*Position, error)

// Increment document name at path n amount.
Increment(ctx context.Context, path string, name string, n int64) (int64, error)
}

// Direction is ascending or descending.
Expand Down
17 changes: 17 additions & 0 deletions dstore/events/events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,20 @@ func TestEventMarshal(t *testing.T) {
`
require.Equal(t, expected, spew.Sdump(out))
}

func TestIncrement(t *testing.T) {
var err error

// keys.SetLogger(keys.NewLogger(keys.DebugLevel))
eds := dstore.NewMem()
clock := tsutil.NewTestClock()
eds.SetClock(clock)

n, err := eds.Increment(context.TODO(), "/test/doc1", "count", 1)
require.NoError(t, err)
require.Equal(t, int64(1), n)

n, err = eds.Increment(context.TODO(), "/test/doc1", "count", 5)
require.NoError(t, err)
require.Equal(t, int64(6), n)
}

0 comments on commit 0b24b65

Please sign in to comment.