summaryrefslogtreecommitdiff
path: root/app/db/in_memory_repository.go
blob: 2aa1fed5462ac9964b234f180adb920a9ff1d8b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
}