package db import ( "context" "sort" "sync" "github.com/xlgmokha/x/pkg/x" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls" ) type inMemoryRepository[T domain.Entity] struct { items []T mu sync.RWMutex } func NewRepository[T domain.Entity]() domain.Repository[T] { return &inMemoryRepository[T]{ items: []T{}, mu: sync.RWMutex{}, } } func (r *inMemoryRepository[T]) All(ctx context.Context) []T { r.mu.RLock() defer r.mu.RUnlock() return r.items } func (r *inMemoryRepository[T]) Find(ctx context.Context, id domain.ID) T { return x.Find(r.All(ctx), func(item T) bool { return item.GetID() == id }) } func (r *inMemoryRepository[T]) Save(ctx context.Context, item T) error { if err := item.Validate(); err != nil { return err } if item.GetID() == "" { item.SetID(domain.ID(pls.GenerateULID())) } r.mu.Lock() defer r.mu.Unlock() r.items = append(r.items, item) sort.Slice(r.items, func(i, j int) bool { return r.items[i].GetID() > r.items[j].GetID() }) return nil }