Skip to content
Snippets Groups Projects
genericStore.go 1.34 KiB
Newer Older
  • Learn to ignore specific revisions
  • André Sterba's avatar
    André Sterba committed
    
    import (
    	"errors"
    
    	"github.com/google/uuid"
    )
    
    type storableConstraint interface {
    	GetID() uuid.UUID
    }
    
    // GenericStore provides a in-memory implementation for multiple stores.
    type GenericStore[T storableConstraint] struct {
    	Store map[uuid.UUID]T
    }
    
    // NewGenericStore returns a specific in-memory store for a type T.
    
    func NewGenericStore[T storableConstraint]() *GenericStore[T] {
    	return &GenericStore[T]{
    
    André Sterba's avatar
    André Sterba committed
    		Store: make(map[uuid.UUID]T),
    	}
    }
    
    func (t *GenericStore[T]) Add(item T) error {
    	_, ok := t.Store[item.GetID()]
    	if ok {
    		return errors.New("item not found")
    	}
    
    	t.Store[item.GetID()] = item
    
    	return nil
    }
    
    func (t *GenericStore[T]) Update(item T) error {
    	_, ok := t.Store[item.GetID()]
    	if ok {
    
    		return errors.New("item not found")
    
    André Sterba's avatar
    André Sterba committed
    	}
    
    	t.Store[item.GetID()] = item
    
    	return nil
    }
    
    func (t *GenericStore[T]) Delete(item T) error {
    
    	_, ok := t.Store[item.GetID()]
    	if ok {
    		return errors.New("item not found")
    	}
    
    
    André Sterba's avatar
    André Sterba committed
    	delete(t.Store, item.GetID())
    
    	return nil
    }
    
    
    func (t *GenericStore[T]) Get(query Query) (T, error) {
    
    André Sterba's avatar
    André Sterba committed
    	// First search for direct hit on UUID.
    	item, ok := t.Store[query.ID]
    	if !ok {
    		return *new(T), errors.New("item not found")
    	}
    
    	return item, nil
    }
    
    func (t *GenericStore[T]) GetAll() ([]T, error) {
    	var allItems []T
    
    	for _, item := range t.Store {
    		allItems = append(allItems, item)
    	}
    
    	return allItems, nil
    }