Added some convenience functions.

This commit is contained in:
jdl 2023-11-20 20:23:44 +01:00
parent ba1990e379
commit 3c9e5505ab

View File

@ -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