-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
39 lines (33 loc) · 969 Bytes
/
transaction.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
package modm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// DoTransactionFunc is a function signature for performing transactions.
type DoTransactionFunc func(
ctx context.Context,
callback func(sessCtx context.Context) (interface{}, error),
opts ...*options.TransactionOptions,
) (interface{}, error)
// DoTransaction creates and manages a database transaction.
func DoTransaction(client *mongo.Client) DoTransactionFunc {
return func(
ctx context.Context,
callback func(sessCtx context.Context) (interface{}, error),
opts ...*options.TransactionOptions,
) (interface{}, error) {
sess, err := client.StartSession()
if err != nil {
return nil, err
}
defer sess.EndSession(ctx)
res, err := sess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
return callback(sessCtx)
}, opts...)
if err != nil {
return nil, err
}
return res, nil
}
}