Skip to content

Commit

Permalink
feat(mongox): support nearest read preference (#42)
Browse files Browse the repository at this point in the history
* feat(mongox): support nearest read preference

* add read pref to client
  • Loading branch information
pyshx authored Jul 25, 2024
1 parent 5cbc45b commit 3b7cfe4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 7 additions & 1 deletion mongox/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (

"github.com/reearth/reearthx/usecasex"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)

Expand All @@ -15,8 +17,12 @@ type Client struct {
}

func NewClient(database string, c *mongo.Client) *Client {
rp := readpref.Nearest()

sessionOpts := options.Database().SetReadPreference(rp)

return &Client{
db: c.Database(database),
db: c.Database(database, sessionOpts),
transaction: &usecasex.NopTransaction{},
}
}
Expand Down
9 changes: 8 additions & 1 deletion mongox/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/reearth/reearthx/usecasex"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver"
)

Expand All @@ -23,7 +24,13 @@ func NewTransaction(client *mongo.Client) *Transaction {
}

func (t *Transaction) Begin(ctx context.Context) (usecasex.Tx, error) {
s, err := t.client.StartSession(options.Session())
// Set the read preference to Nearest
rp := readpref.Nearest()

// Create session options with the Nearest read preference
sessionOpts := options.Session().SetDefaultReadPreference(rp)

s, err := t.client.StartSession(sessionOpts)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 3b7cfe4

Please sign in to comment.