From 3c9e5505ab49ba8cd025c00a6da90ad672443313 Mon Sep 17 00:00:00 2001 From: jdl Date: Mon, 20 Nov 2023 20:23:44 +0100 Subject: [PATCH] Added some convenience functions. --- mdb/collection.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/mdb/collection.go b/mdb/collection.go index 73b035d..a443563 100644 --- a/mdb/collection.go +++ b/mdb/collection.go @@ -108,13 +108,14 @@ type indexConfig[T any] struct { Include func(item *T) bool } +// A shortcut for c.ByID.Get(tx, &Item{ID:id}). func (c *Collection[T]) Get(tx *Snapshot, id uint64) (*T, bool) { x := new(T) c.setID(x, id) return c.ByID.Get(tx, x) } -func (c *Collection[T]) List(tx *Snapshot, ids []uint64, out []*T) []*T { +func (c *Collection[T]) GetList(tx *Snapshot, ids []uint64, out []*T) []*T { if len(ids) == 0 { return out[:0] } @@ -234,6 +235,18 @@ func (c *Collection[T]) Update(tx *Snapshot, userItem *T) error { return nil } +func (c *Collection[T]) UpdateFunc(tx *Snapshot, id uint64, update func(item *T) error) error { + item, ok := c.getByID(tx, id) + if !ok { + return errs.NotFound + } + itemCopy := c.copy(item) + if err := update(itemCopy); err != nil { + return err + } + return c.Update(tx, itemCopy) +} + func (c *Collection[T]) Upsert(tx *Snapshot, item *T) error { err := c.Insert(tx, item) if err == nil { @@ -245,6 +258,20 @@ func (c *Collection[T]) Upsert(tx *Snapshot, item *T) error { return err } +func (c *Collection[T]) UpsertFunc(tx *Snapshot, id uint64, update func(item *T) error) error { + item, ok := c.getByID(tx, id) + if !ok { + item = new(T) + c.setID(item, id) + } + + itemCopy := c.copy(item) + if err := update(itemCopy); err != nil { + return err + } + return c.Upsert(tx, itemCopy) +} + func (c *Collection[T]) Delete(tx *Snapshot, itemID uint64) error { if err := c.ensureMutable(tx); err != nil { return err