summaryrefslogtreecommitdiff
path: root/pkg/db/repository.go
blob: d8a59903542c38cdeb170d011150bfc46e75f967 (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
package db

import (
	"gitlab.com/mokhax/sparkled/pkg/domain"
	"gitlab.com/mokhax/sparkled/pkg/pls"
)

type Repository interface {
	All() []*domain.Sparkle
	Each(func(*domain.Sparkle))
	Save(*domain.Sparkle) error
}

type inMemoryRepository struct {
	sparkles []*domain.Sparkle
}

func NewRepository() Repository {
	return &inMemoryRepository{
		sparkles: []*domain.Sparkle{},
	}
}

func (r *inMemoryRepository) All() []*domain.Sparkle {
	return r.sparkles
}

func (r *inMemoryRepository) Each(visitor func(item *domain.Sparkle)) {
	for _, item := range r.All() {
		visitor(item)
	}
}

func (r *inMemoryRepository) Save(item *domain.Sparkle) error {
	if err := item.Validate(); err != nil {
		return err
	}

	if item.ID == "" {
		item.ID = pls.GenerateULID()
	}

	r.sparkles = append(r.sparkles, item)
	return nil
}