-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmove-entity-ev.go
97 lines (77 loc) · 2.01 KB
/
move-entity-ev.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package event
import (
"context"
"fmt"
"github.com/HouzuoGuo/tiedot/db"
"github.com/ajainc/chain/ctx/docdb"
"github.com/ajainc/chain/event/dao"
"github.com/ajainc/chain/grpc/gen"
uuid "github.com/satori/go.uuid"
)
// NewMoveEntityEvent stands for Move Entity to specified coordinates
func NewMoveEntityEvent(entityObjectID string, from gen.Coord, to gen.Coord) *MoveEntityEv {
return &MoveEntityEv{
eventID: uuid.NewV4().String(),
entityObjectID: entityObjectID,
from: from,
to: to,
}
}
type MoveEntityEv struct {
eventID string
entityObjectID string
from gen.Coord
to gen.Coord
}
func (ev *MoveEntityEv) EventID() string {
return ev.eventID
}
func (ev *MoveEntityEv) Description() string {
return fmt.Sprintf("Move Entity")
}
func (ev *MoveEntityEv) Exec(c context.Context) error {
db := docdb.FromContext(c)
err := ev.Validate(db)
if err != nil {
return err
}
id, entity, err := dao.GetEntityByObjectID(c, ev.entityObjectID)
if err != nil {
return err
}
entity.Coord = &ev.to
err = dao.UpdateEntity(c, id, entity)
return err
}
func (ev *MoveEntityEv) Validate(db *db.DB) error {
if !docdb.ObjectIDExists(db, docdb.COLL_ENTITY, ev.entityObjectID) {
return fmt.Errorf("entity object <%s> not exists", ev.entityObjectID)
}
return nil
}
func (ev *MoveEntityEv) ExecStreamPayloads(c context.Context) ([]*gen.StreamPayload, error) {
_, entity, err := dao.GetEntityByObjectID(c, ev.entityObjectID)
if err != nil {
return nil, err
}
return []*gen.StreamPayload{
{
Operation: gen.StreamPayload_MOD,
Object: &gen.StreamPayload_Entity{
&entity,
},
},
}, nil
}
func (ev *MoveEntityEv) Undo(c context.Context) error {
id, entity, err := dao.GetEntityByObjectID(c, ev.entityObjectID)
if err != nil {
return err
}
entity.Coord = &ev.from
err = dao.UpdateEntity(c, id, entity)
return err
}
func (ev *MoveEntityEv) UndoStreamPayloads(c context.Context) ([]*gen.StreamPayload, error) {
return ev.ExecStreamPayloads(c)
}