-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsettings.go
102 lines (79 loc) · 2.21 KB
/
settings.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
98
99
100
101
102
package mongo
import (
"go.mongodb.org/mongo-driver/mongo/options"
trm "github.com/avito-tech/go-transaction-manager/trm/v2"
)
// Opt is a type to configure Settings.
type Opt func(*Settings) error
// WithSessionOpts sets up options.SessionOptions for the Settings.
func WithSessionOpts(opts *options.SessionOptions) Opt {
return func(s *Settings) error {
*s = s.setSessionOpts(opts)
return nil
}
}
// WithTransactionOpts sets up options.TransactionOptions for the Settings.
func WithTransactionOpts(opts *options.TransactionOptions) Opt {
return func(s *Settings) error {
*s = s.setTransactionOpts(opts)
return nil
}
}
// Settings contains settings for mongo.Transaction.
type Settings struct {
trm.Settings
sessionOpts *options.SessionOptions
transactionOpts *options.TransactionOptions
}
// NewSettings creates Settings.
func NewSettings(trms trm.Settings, oo ...Opt) (Settings, error) {
s := &Settings{
Settings: trms,
sessionOpts: nil,
transactionOpts: nil,
}
for _, o := range oo {
if err := o(s); err != nil {
return Settings{}, err
}
}
return *s, nil
}
// MustSettings returns Settings if err is nil and panics otherwise.
func MustSettings(trms trm.Settings, oo ...Opt) Settings {
s, err := NewSettings(trms, oo...)
if err != nil {
panic(err)
}
return s
}
// EnrichBy fills nil properties from external Settings.
func (s Settings) EnrichBy(in trm.Settings) trm.Settings {
external, ok := in.(Settings)
if ok {
if s.SessionOpts() == nil {
s = s.setSessionOpts(external.SessionOpts())
}
if s.TransactionOpts() == nil {
s = s.setTransactionOpts(external.TransactionOpts())
}
}
s.Settings = s.Settings.EnrichBy(in)
return s
}
// SessionOpts returns *options.SessionOptions for the trm.Transaction.
func (s Settings) SessionOpts() *options.SessionOptions {
return s.sessionOpts
}
func (s Settings) setSessionOpts(opts *options.SessionOptions) Settings {
s.sessionOpts = opts
return s
}
// TransactionOpts returns trm.CtxKey for the trm.Transaction.
func (s Settings) TransactionOpts() *options.TransactionOptions {
return s.transactionOpts
}
func (s Settings) setTransactionOpts(opts *options.TransactionOptions) Settings {
s.transactionOpts = opts
return s
}