-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
aggregate_repository.go
76 lines (61 loc) · 1.65 KB
/
aggregate_repository.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
71
72
73
74
75
76
package es
import (
"context"
"fmt"
"github.com/LordMoMA/Intelli-Mall/internal/ddd"
"github.com/LordMoMA/Intelli-Mall/internal/registry"
)
type (
AggregateRepository[T EventSourcedAggregate] interface {
Load(ctx context.Context, aggregateID string) (agg T, err error)
Save(ctx context.Context, aggregate T) error
}
aggregateRepository[T EventSourcedAggregate] struct {
aggregateName string
registry registry.Registry
store AggregateStore
}
)
var _ AggregateRepository[EventSourcedAggregate] = (*aggregateRepository[EventSourcedAggregate])(nil)
func NewAggregateRepository[T EventSourcedAggregate](aggregateName string, registry registry.Registry, store AggregateStore) aggregateRepository[T] {
return aggregateRepository[T]{
aggregateName: aggregateName,
registry: registry,
store: store,
}
}
func (r aggregateRepository[T]) Load(ctx context.Context, aggregateID string) (agg T, err error) {
var v any
v, err = r.registry.Build(
r.aggregateName,
ddd.SetID(aggregateID),
ddd.SetName(r.aggregateName),
)
if err != nil {
return agg, err
}
var ok bool
if agg, ok = v.(T); !ok {
return agg, fmt.Errorf("%T is not the expected type %T", v, agg)
}
if err = r.store.Load(ctx, agg); err != nil {
return agg, err
}
return agg, nil
}
func (r aggregateRepository[T]) Save(ctx context.Context, aggregate T) error {
if aggregate.Version() == aggregate.PendingVersion() {
return nil
}
for _, event := range aggregate.Events() {
if err := aggregate.ApplyEvent(event); err != nil {
return err
}
}
err := r.store.Save(ctx, aggregate)
if err != nil {
return err
}
aggregate.CommitEvents()
return nil
}