forked from violetpay-org/go-saga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saga.go
69 lines (56 loc) · 1.7 KB
/
saga.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
package saga
import (
"fmt"
"github.com/google/uuid"
"strings"
)
func convertSaga[S Session, Tx TxContext](src Saga[S, Tx]) Saga[Session, Tx] {
var factory SessionFactory[Session]
factory = func(args map[string]interface{}) Session {
sess := src.factory(args)
return sess
}
var repository SessionRepository[Session, Tx]
repository = &sessionRepository[Tx]{
load: func(id string) (Session, error) { return src.repository.Load(id) },
save: func(sess Session) Executable[Tx] { return src.repository.Save(sess.(S)) },
delete: func(sess Session) Executable[Tx] { return src.repository.Delete(sess.(S)) },
}
return NewSaga[Session, Tx](src.name, src.definition, factory, repository)
}
type Saga[S Session, Tx TxContext] struct {
name string
definition Definition
factory SessionFactory[S]
repository SessionRepository[S, Tx]
}
func NewSaga[S Session, Tx TxContext](name string, def Definition, factory SessionFactory[S], repository SessionRepository[S, Tx]) Saga[S, Tx] {
return Saga[S, Tx]{
name: name,
definition: def,
factory: factory,
repository: repository,
}
}
func (s *Saga[S, Tx]) Name() string {
return s.name
}
func (s *Saga[S, Tx]) Definition() Definition {
return s.definition
}
func (s *Saga[S, Tx]) Repository() SessionRepository[S, Tx] {
return s.repository
}
func (s *Saga[S, Tx]) createSession(args map[string]interface{}) S {
if args["id"] == nil {
args["id"] = fmt.Sprintf("%s-%s", s.name, uuid.New().String())
}
return s.factory(args)
}
func extractSagaName(sessid string) string {
return strings.Split(sessid, "-")[0]
}
func (s *Saga[S, Tx]) hasPublishedSaga(sessid string) bool {
sagaName := extractSagaName(sessid)
return s.name == sagaName
}