-
Notifications
You must be signed in to change notification settings - Fork 1
/
dbSave.go
43 lines (35 loc) · 1.18 KB
/
dbSave.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
package quantification
import (
"context"
"github.com/pixlise/core/v4/api/dbCollections"
protos "github.com/pixlise/core/v4/generated-protos"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
func writeQuantAndOwnershipToDB(summary *protos.QuantificationSummary, owner *protos.OwnershipItem, db *mongo.Database) error {
ctx := context.TODO()
wc := writeconcern.New(writeconcern.WMajority())
rc := readconcern.Snapshot()
txnOpts := options.Transaction().SetWriteConcern(wc).SetReadConcern(rc)
sess, err := db.Client().StartSession()
if err != nil {
return err
}
defer sess.EndSession(ctx)
// Write the 2 items in a single transaction
callback := func(sessCtx mongo.SessionContext) (interface{}, error) {
_, _err := db.Collection(dbCollections.QuantificationsName).InsertOne(sessCtx, summary)
if _err != nil {
return nil, _err
}
_, _err = db.Collection(dbCollections.OwnershipName).InsertOne(sessCtx, owner)
if _err != nil {
return nil, _err
}
return nil, nil
}
_, err = sess.WithTransaction(ctx, callback, txnOpts)
return err
}