/
transactor.go
44 lines (35 loc) · 1.52 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
// Package transactor contains logic for mongo-driver transactional behavior
package transactor
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// MongoDriverTransactor represents mongodb transactor behavior
type MongoDriverTransactor interface {
WithinTransaction(ctx context.Context, txFn func(context.Context) error) error
WithinTransactionWithOptions(ctx context.Context, txFn func(context.Context) error, opts ...*options.TransactionOptions) error
}
type mongoDriverTransactor struct {
client *mongo.Client
}
// NewMongoDriverTransactor builds new MongoDriverTransactor
func NewMongoDriverTransactor(client *mongo.Client) MongoDriverTransactor {
return &mongoDriverTransactor{client: client}
}
// WithinTransaction runs WithinTransactionWithOptions with default tx options
func (t *mongoDriverTransactor) WithinTransaction(ctx context.Context, txFn func(context.Context) error) error {
return t.WithinTransactionWithOptions(ctx, txFn)
}
// WithinTransactionWithOptions runs logic within transaction passing context with transaction injected into it specifying options
func (t *mongoDriverTransactor) WithinTransactionWithOptions(ctx context.Context, txFn func(context.Context) error, opts ...*options.TransactionOptions) error {
session, err := t.client.StartSession()
if err != nil {
return err
}
defer session.EndSession(ctx)
_, err = session.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (any, error) {
return nil, txFn(sessCtx)
}, opts...)
return err
}