diff --git a/dstore/events.go b/dstore/events.go index 6b008dd..a00d839 100644 --- a/dstore/events.go +++ b/dstore/events.go @@ -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{} diff --git a/dstore/events/events.go b/dstore/events/events.go index 7929965..9d1f3ef 100644 --- a/dstore/events/events.go +++ b/dstore/events/events.go @@ -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. diff --git a/dstore/events/events_test.go b/dstore/events/events_test.go index 016f92c..f9724ed 100644 --- a/dstore/events/events_test.go +++ b/dstore/events/events_test.go @@ -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) +}