31 lines
632 B
Go
31 lines
632 B
Go
package transactionimp
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/tech/sendico/pkg/db/transaction"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
)
|
|
|
|
type MongoTransaction struct {
|
|
client *mongo.Client
|
|
}
|
|
|
|
func (mt *MongoTransaction) Execute(ctx context.Context, cb transaction.Callback) (any, error) {
|
|
session, err := mt.client.StartSession()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer session.EndSession(ctx)
|
|
|
|
callback := func(sessCtx mongo.SessionContext) (any, error) {
|
|
return cb(sessCtx)
|
|
}
|
|
|
|
return session.WithTransaction(ctx, callback)
|
|
}
|
|
|
|
func Create(client *mongo.Client) *MongoTransaction {
|
|
return &MongoTransaction{client: client}
|
|
}
|