This repository has been archived by the owner on Aug 30, 2023. It is now read-only.
/
transactor.go
56 lines (47 loc) · 1.67 KB
/
transactor.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
package gotx
import (
"context"
)
type DoInTransaction func(ctx context.Context) error
type Transactor interface {
// Support a current transaction, create a new one if none exists.
Required(ctx context.Context, fn DoInTransaction, options ...Option) error
// Create a new transaction, and suspend the current transaction if one exists.
RequiresNew(ctx context.Context, fn DoInTransaction, options ...Option) (err error)
}
type CompositeTransactor struct {
transactors []Transactor
}
func NewCompositeTransactor(transactors ...Transactor) *CompositeTransactor {
return &CompositeTransactor{
transactors: transactors,
}
}
func (t *CompositeTransactor) Required(ctx context.Context, fn DoInTransaction, options ...Option) error {
composed := fn
for _, transactor := range t.transactors {
composed = t.composeRequired(transactor, composed, options...)
}
return composed(ctx)
}
func (t *CompositeTransactor) composeRequired(a Transactor, composed DoInTransaction, options ...Option) DoInTransaction {
return func(ctx context.Context) error {
return a.Required(ctx, func(ctx context.Context) error {
return composed(ctx)
}, options...)
}
}
func (t *CompositeTransactor) RequiresNew(ctx context.Context, fn DoInTransaction, options ...Option) error {
composed := fn
for _, transactor := range t.transactors {
composed = t.composeRequiresNew(transactor, composed, options...)
}
return composed(ctx)
}
func (t *CompositeTransactor) composeRequiresNew(a Transactor, composed DoInTransaction, options ...Option) DoInTransaction {
return func(ctx context.Context) error {
return a.RequiresNew(ctx, func(ctx context.Context) error {
return composed(ctx)
}, options...)
}
}