-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit-of-work.go
59 lines (50 loc) · 1.62 KB
/
unit-of-work.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
package shared
import (
"context"
ycq "github.com/jetbasrawi/go.cqrs"
"reflect"
)
type GenericUnitOfWork interface {
GetAggregateRepo(aggregateType reflect.Type) Repository
Load(typ reflect.Type, aggregateID string) (ycq.AggregateRoot, error)
Save(aggregate ycq.AggregateRoot, expectedVersion *int) error
CommitAllChanges(ctx context.Context, transaction interface{}) error
AcceptAllChanges()
}
type AggregateDefinition struct {
Constructor func(id string) ycq.AggregateRoot
Type reflect.Type
}
type BaseGenericUnitOfWork struct {
Repos map[string]Repository
}
func NewBaseGenericUnitOfWork() *BaseGenericUnitOfWork {
return &BaseGenericUnitOfWork{Repos: map[string]Repository{}}
}
func (uow *BaseGenericUnitOfWork) GetAggregateRepo(aggregateType reflect.Type) Repository {
typeString := aggregateType.String()
return uow.Repos[typeString]
}
func (uow *BaseGenericUnitOfWork) Load(typ reflect.Type, aggregateID string) (ycq.AggregateRoot, error) {
return uow.Repos[typ.String()].Load(aggregateID)
}
func (uow *BaseGenericUnitOfWork) Save(aggregate ycq.AggregateRoot, expectedVersion *int) error {
aggregateType := reflect.TypeOf(aggregate).String()
repo := uow.Repos[aggregateType]
return repo.Save(aggregate, expectedVersion)
}
func (uow *BaseGenericUnitOfWork) CommitAllChanges(ctx context.Context, transaction interface{}) error {
var err error = nil
for _, repository := range uow.Repos {
err = repository.CommitChanges(ctx, transaction)
if err != nil {
break
}
}
return err
}
func (uow *BaseGenericUnitOfWork) AcceptAllChanges() {
for _, repository := range uow.Repos {
repository.AcceptChanges()
}
}