Skip to content

Commit

Permalink
mongo: add client options config
Browse files Browse the repository at this point in the history
  • Loading branch information
agungdwiprasetyo committed Jan 3, 2024
1 parent 103fb7b commit ff8f055
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions config/database/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package database

import (
"context"
"fmt"
"log"
"sync"
"time"

Expand Down Expand Up @@ -56,42 +56,40 @@ func (m *mongoInstance) Disconnect(ctx context.Context) (err error) {

// InitMongoDB return mongo db read & write instance from environment:
// MONGODB_HOST_WRITE, MONGODB_HOST_READ
func InitMongoDB(ctx context.Context) interfaces.MongoDatabase {
func InitMongoDB(ctx context.Context, opts ...*options.ClientOptions) interfaces.MongoDatabase {
deferFunc := logger.LogWithDefer("Load MongoDB connection...")
defer deferFunc()

mi := &mongoInstance{}
if env.BaseEnv().DbMongoReadHost != "" {
mi.read = ConnectMongoDB(ctx, env.BaseEnv().DbMongoReadHost)
mi.read = ConnectMongoDB(ctx, env.BaseEnv().DbMongoReadHost, opts...)
}
if env.BaseEnv().DbMongoWriteHost != "" {
mi.write = ConnectMongoDB(ctx, env.BaseEnv().DbMongoWriteHost)
mi.write = ConnectMongoDB(ctx, env.BaseEnv().DbMongoWriteHost, opts...)
}
return mi
}

// ConnectMongoDB connect to mongodb with dsn
func ConnectMongoDB(ctx context.Context, dsn string) *mongo.Database {
func ConnectMongoDB(ctx context.Context, dsn string, opts ...*options.ClientOptions) *mongo.Database {
connDSN, err := connstring.ParseAndValidate(dsn)
if err != nil {
log.Panic(err)
}

clientOpts := []*options.ClientOptions{
options.Client().ApplyURI(connDSN.String()),
options.Client().SetConnectTimeout(10 * time.Second),
options.Client().SetServerSelectionTimeout(10 * time.Second),
}
clientOpts = append(clientOpts, opts...)

// get mongo dsn from env
connDSN, err := connstring.ParseAndValidate(dsn)
if err != nil {
panic(err)
}
// connect to MongoDB
client, err := mongo.NewClient(append([]*options.ClientOptions{options.Client().ApplyURI(connDSN.String())}, clientOpts...)...)
client, err := mongo.Connect(ctx, clientOpts...)
if err != nil {
panic(fmt.Sprintf("mongodb: %v, conn: %s", err, connDSN.String()))
}
if err := client.Connect(ctx); err != nil {
panic(fmt.Sprintf("mongodb error connect: %v", err))
log.Panicf("mongodb: %v, conn: %s", err, connDSN.String())
}
if err = client.Ping(ctx, readpref.Primary()); err != nil {
panic(fmt.Sprintf("mongodb ping: %v", err))
log.Panicf("mongodb ping: %v", err)
}

return client.Database(connDSN.Database)
Expand Down

0 comments on commit ff8f055

Please sign in to comment.