-
Notifications
You must be signed in to change notification settings - Fork 0
/
battle_repository.go
49 lines (38 loc) · 989 Bytes
/
battle_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
package inmemory
import (
"context"
"github.com/elct9620/wvs/internal/db"
"github.com/elct9620/wvs/internal/entity/battle"
"github.com/elct9620/wvs/internal/usecase"
)
var _ usecase.BattleRepository = &BattleRepository{}
type BattleRepository struct {
db *db.Database
}
func NewBattleRepository(db *db.Database) *BattleRepository {
return &BattleRepository{
db: db,
}
}
func (r *BattleRepository) Save(ctx context.Context, entity *battle.Battle) error {
txn := r.db.Txn(true)
defer txn.Abort()
events := entity.PendingEvents()
currentVersion := entity.Version()
nextVersion := currentVersion - len(events) + 1
for idx, evt := range events {
record := &db.BattleEvent{
Id: evt.Id(),
AggregateId: evt.AggregateId(),
Type: evt.Type(),
Version: nextVersion + idx,
CreatedAt: evt.CreatedAt(),
}
if err := txn.Insert(db.TableBattle, record); err != nil {
return err
}
}
txn.Commit()
entity.ClearEvents()
return nil
}