-
Notifications
You must be signed in to change notification settings - Fork 0
/
uow.go
70 lines (55 loc) · 1.48 KB
/
uow.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package initialize
import (
"context"
"errors"
"github.com/devdammit/shekel/cmd/unit/internal/entities"
"github.com/devdammit/shekel/internal/resources"
"github.com/devdammit/shekel/pkg/types/datetime"
"go.etcd.io/bbolt"
)
type appConfigRepository interface {
SetStartDateTx(ctx context.Context, tx *bbolt.Tx, date datetime.Date) error
}
type periodsRepository interface {
CreateTx(ctx context.Context, tx *bbolt.Tx, period entities.Period) (*entities.Period, error)
}
type UoW struct {
startDate *datetime.Date
periods []entities.Period
db *resources.Bolt
periodsRepo periodsRepository
appConfig appConfigRepository
}
func NewUoW(db *resources.Bolt, repository appConfigRepository, periodsRepository periodsRepository) *UoW {
return &UoW{
appConfig: repository,
db: db,
periodsRepo: periodsRepository,
periods: make([]entities.Period, 0),
}
}
func (u *UoW) SetStartDate(date datetime.Date) {
u.startDate = &date
}
func (u *UoW) CreatePeriod(period entities.Period) error {
u.periods = append(u.periods, period)
return nil
}
func (u *UoW) Commit(ctx context.Context) error {
if u.startDate == nil || u.periods == nil {
return errors.New("missing data")
}
return u.db.Update(func(tx *bbolt.Tx) error {
err := u.appConfig.SetStartDateTx(ctx, tx, *u.startDate)
if err != nil {
return err
}
for _, period := range u.periods {
_, err = u.periodsRepo.CreateTx(ctx, tx, period)
if err != nil {
return err
}
}
return nil
})
}