Skip to content

Commit 5553829

Browse files
authored
Merge pull request #17 from taimaifika/release/v1.5.3
Enhance MongoDB component with additional configuration options and methods
2 parents 91e64d3 + f287f96 commit 5553829

File tree

5 files changed

+101
-26
lines changed

5 files changed

+101
-26
lines changed

component/mongodbc/mongodbc.go

Lines changed: 73 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package mongodbc
22

33
import (
44
"context"
5+
"errors"
56
"flag"
67
"log/slog"
78
"time"
@@ -13,10 +14,16 @@ import (
1314
)
1415

1516
type config struct {
16-
url string
17-
username string
18-
password string
19-
timeout time.Duration
17+
url string
18+
username string
19+
password string
20+
authMechanism string
21+
authSource string
22+
maxPoolSize uint64
23+
minPoolSize uint64
24+
timeout time.Duration
25+
connectionTimeout time.Duration
26+
ServerSelectionTimeout time.Duration
2027
}
2128

2229
type mongoDbComponent struct {
@@ -34,39 +41,93 @@ func NewMongoDbComponent(id string) *mongoDbComponent {
3441
}
3542
}
3643

44+
// GetMongoClient returns the mongo client
3745
func (m *mongoDbComponent) GetMongoClient() *mongo.Client {
3846
return m.mongoClient
3947
}
4048

49+
// GetMongoClientWithName returns the mongo client with the given name in config
50+
func (m *mongoDbComponent) GetDatabase() *mongo.Database {
51+
return m.mongoClient.Database(m.config.authSource)
52+
}
53+
54+
// GetCollection returns the mongo client with the given collection name
55+
func (m *mongoDbComponent) GetCollection(collectionName string) *mongo.Collection {
56+
return m.mongoClient.Database(m.config.authSource).Collection(collectionName)
57+
}
58+
59+
// GetDatabaseName returns the mongo client with the given name in config
60+
func (m *mongoDbComponent) GetDatabaseName() string {
61+
return m.config.authSource
62+
}
63+
64+
// GetDatabaseWithName returns the mongo client with the given name
65+
func (m *mongoDbComponent) GetDatabaseWithName(dbName string) *mongo.Database {
66+
return m.mongoClient.Database(dbName)
67+
}
68+
69+
// GetCollection returns the mongo client with the given name
70+
func (m *mongoDbComponent) GetCollectionWithDatabase(dbName, collectionName string) *mongo.Collection {
71+
return m.mongoClient.Database(dbName).Collection(collectionName)
72+
}
73+
4174
func (m *mongoDbComponent) ID() string {
4275
return m.id
4376
}
4477

4578
func (m *mongoDbComponent) InitFlags() {
4679
flag.StringVar(&m.url, m.id+"-url", "mongodb://localhost:27017", "redis urls. default: mongodb://localhost:27017")
47-
flag.StringVar(&m.username, m.id+"-username", "", "redis username. default: ''")
48-
flag.StringVar(&m.password, m.id+"-password", "", "redis password. default: ''")
4980

50-
flag.DurationVar(&m.timeout, m.id+"-timeout", 10*time.Second, "redis timeout. default: 10s")
81+
flag.StringVar(&m.username, m.id+"-username", "", "mongodb username. default: ''")
82+
flag.StringVar(&m.password, m.id+"-password", "", "mongodb password. default: ''")
83+
flag.StringVar(&m.authMechanism, m.id+"-auth-mechanism", "SCRAM-SHA-256", "AuthMechanism supported values include SCRAM-SHA-256, SCRAM-SHA-1, MONGODB-CR, PLAIN, GSSAPI, MONGODB-X509, and MONGODB-AWS. default: 'SCRAM-SHA-256'")
84+
flag.StringVar(&m.authSource, m.id+"-auth-source", "", "AuthSource. default: ''")
85+
86+
flag.Uint64Var(&m.minPoolSize, m.id+"-min-pool-size", 10, "mongodb min pool size. default: 10")
87+
flag.Uint64Var(&m.maxPoolSize, m.id+"-max-pool-size", 100, "mongodb max pool size. default: 100")
88+
89+
flag.DurationVar(&m.timeout, m.id+"-timeout", 10*time.Second, "mongodb timeout. default: 10s")
90+
flag.DurationVar(&m.connectionTimeout, m.id+"-connection-timeout", 30*time.Second, "mongodb connection timeout. default: 30s")
91+
flag.DurationVar(&m.ServerSelectionTimeout, m.id+"-server-selection-timeout", 30*time.Second, "mongodb server selection timeout. default: 30s")
92+
5193
}
5294

5395
func (m *mongoDbComponent) Activate(ctx sctx.ServiceContext) error {
5496
// create mongo client
5597
opts := options.Client()
5698
// set url
5799
opts.ApplyURI(m.url)
100+
101+
// set min pool size
102+
opts.SetMinPoolSize(m.minPoolSize)
103+
104+
// set max pool size
105+
opts.SetMaxPoolSize(m.maxPoolSize)
106+
58107
// set timeout
59108
opts.SetTimeout(m.timeout)
60109

61-
// set auth
110+
// set connection timeout
111+
opts.SetConnectTimeout(m.connectionTimeout)
112+
113+
// set ConnectTimeout
114+
opts.SetServerSelectionTimeout(m.ServerSelectionTimeout)
115+
116+
// set auth database
62117
if m.username != "" && m.password != "" {
63118
opts.SetAuth(options.Credential{
64-
Username: m.username,
65-
Password: m.password,
119+
Username: m.username,
120+
Password: m.password,
121+
AuthMechanism: m.authMechanism,
122+
AuthSource: m.authSource,
66123
})
67124
}
125+
// validate auth source, return err
126+
if opts.Auth.AuthSource == "" {
127+
return errors.New("auth source is empty")
128+
}
68129

69-
slog.Info("Connecting to mongo db")
130+
slog.Info("Connecting to mongo db ...")
70131

71132
client, err := mongo.Connect(opts)
72133
if err != nil {
@@ -81,7 +142,7 @@ func (m *mongoDbComponent) Activate(ctx sctx.ServiceContext) error {
81142

82143
m.mongoClient = client
83144

84-
slog.Info("Connect to mongo db success")
145+
slog.Info("Connect to mongo db success !!!")
85146

86147
return nil
87148
}

examples/mongodbcomp/.env.example

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,33 @@
11
# Env for service. Ex: dev | stg | prd (-app-env)
22
APP_ENV="dev"
33

4-
# Log format: text | json . Default json (-log-format)
5-
LOG_FORMAT="json"
4+
# AuthMechanism supported values include SCRAM-SHA-256, SCRAM-SHA-1, MONGODB-CR, PLAIN, GSSAPI, MONGODB-X509, and MONGODB-AWS. default: 'SCRAM-SHA-256' (-mongodb-auth-mechanism)
5+
MONGODB_AUTH_MECHANISM="SCRAM-SHA-256"
66

7-
# Log level: panic | fatal | error | warn | info | debug | trace (-log-level)
8-
LOG_LEVEL="trace"
7+
# AuthSource. default: '' (-mongodb-auth-source)
8+
MONGODB_AUTH_SOURCE=
99

10-
# redis password. default: '' (-mongodb-password)
10+
# mongodb connection timeout. default: 30s (-mongodb-connection-timeout)
11+
MONGODB_CONNECTION_TIMEOUT=30s
12+
13+
# mongodb max pool size. default: 100 (-mongodb-max-pool-size)
14+
MONGODB_MAX_POOL_SIZE=100
15+
16+
# mongodb min pool size. default: 10 (-mongodb-min-pool-size)
17+
MONGODB_MIN_POOL_SIZE=10
18+
19+
# mongodb password. default: '' (-mongodb-password)
1120
MONGODB_PASSWORD=
1221

13-
# redis timeout. default: 10s (-mongodb-timeout)
22+
# mongodb server selection timeout. default: 30s (-mongodb-server-selection-timeout)
23+
MONGODB_SERVER_SELECTION_TIMEOUT=30s
24+
25+
# mongodb timeout. default: 10s (-mongodb-timeout)
1426
MONGODB_TIMEOUT=10s
1527

1628
# redis urls. default: mongodb://localhost:27017 (-mongodb-url)
1729
MONGODB_URL="mongodb://localhost:27017"
1830

19-
# redis username. default: '' (-mongodb-username)
31+
# mongodb username. default: '' (-mongodb-username)
2032
MONGODB_USERNAME=
2133

examples/mongodbcomp/cmd/root.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ func newServiceCtx() sctx.ServiceContext {
2222

2323
type MongoDbComponent interface {
2424
GetMongoClient() *mongo.Client
25+
GetDatabaseName() string
2526
}
2627

2728
var rootCmd = &cobra.Command{
@@ -38,17 +39,18 @@ var rootCmd = &cobra.Command{
3839
// get mongodb component
3940
mongoDbComponent := serviceCtx.MustGet("mongodb").(MongoDbComponent)
4041
mongoClient := mongoDbComponent.GetMongoClient()
42+
databaseName := mongoDbComponent.GetDatabaseName()
4143

4244
// insert data
43-
res, err := mongoClient.Database("test").Collection("test").InsertOne(context.Background(), map[string]string{"test": "test"})
45+
res, err := mongoClient.Database(databaseName).Collection("test").InsertOne(context.Background(), map[string]string{"test": "test"})
4446
if err != nil {
4547
slog.Error("insert data error", "error", err)
4648
}
4749
fmt.Println(res)
4850

4951
// get all data
5052
var result []map[string]interface{}
51-
cursor, err := mongoClient.Database("test").Collection("test").Find(
53+
cursor, err := mongoClient.Database(databaseName).Collection("test").Find(
5254
context.Background(), bson.M{
5355
"test": "test",
5456
})
@@ -73,15 +75,15 @@ var rootCmd = &cobra.Command{
7375
slog.Error("convert id to object id error", "error", err)
7476
}
7577
filter := bson.M{"_id": objID}
76-
err = mongoClient.Database("test").Collection("test").FindOne(
78+
err = mongoClient.Database(databaseName).Collection("test").FindOne(
7779
context.Background(), filter).Decode(&resultOne)
7880
if err != nil {
7981
slog.Error("find one data error", "error", err)
8082
}
8183
fmt.Println(resultOne)
8284

8385
// delete data
84-
_, err = mongoClient.Database("test").Collection("test").DeleteOne(context.Background(), bson.M{"test": "test"})
86+
_, err = mongoClient.Database(databaseName).Collection("test").DeleteOne(context.Background(), bson.M{"test": "test"})
8587
if err != nil {
8688
slog.Error("delete data error", "error", err)
8789
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ require (
114114
github.com/spf13/pflag v1.0.6 // indirect
115115
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
116116
github.com/ugorji/go/codec v1.2.12 // indirect
117-
go.mongodb.org/mongo-driver/v2 v2.1.0
117+
go.mongodb.org/mongo-driver/v2 v2.2.0
118118
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.60.0
119119
golang.org/x/arch v0.15.0 // indirect
120120
golang.org/x/crypto v0.36.0 // indirect

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi
237237
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
238238
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
239239
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
240-
go.mongodb.org/mongo-driver/v2 v2.1.0 h1:/ELnVNjmfUKDsoBisXxuJL0noR9CfeUIrP7Yt3R+egg=
241-
go.mongodb.org/mongo-driver/v2 v2.1.0/go.mod h1:AWiLRShSrk5RHQS3AEn3RL19rqOzVq49MCpWQ3x/huI=
240+
go.mongodb.org/mongo-driver/v2 v2.2.0 h1:WwhNgGrijwU56ps9RtIsgKfGLEZeypxqbEYfThrBScM=
241+
go.mongodb.org/mongo-driver/v2 v2.2.0/go.mod h1:qQkDMhCGWl3FN509DfdPd4GRBLU/41zqF/k8eTRceps=
242242
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
243243
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
244244
go.opentelemetry.io/contrib/bridges/otelslog v0.10.0 h1:lRKWBp9nWoBe1HKXzc3ovkro7YZSb72X2+3zYNxfXiU=

0 commit comments

Comments
 (0)