diff --git a/db/mongo.go b/db/mongo.go index 8cff787..69432dc 100644 --- a/db/mongo.go +++ b/db/mongo.go @@ -42,7 +42,7 @@ func (c *MongoConfig) validate() error { if c.Port == "" || c.Port == "0" { c.Port = "27017" } else { - if _, err := strconv.Atoi(c.Port); err == nil { + if _, err := strconv.Atoi(c.Port); err != nil { return errors.Wrap(errors.InvalidArgument, "invalid database port") } } @@ -61,7 +61,7 @@ func NewMongoClient(conf *MongoConfig) (StoreClient, error) { clientOptions.ApplyURI(uri) clientOptions.SetAuth(options.Credential{ AuthMechanism: "SCRAM-SHA-256", - AuthSource: getSourceIdentifier(), + AuthSource: "admin", //getSourceIdentifier(), Username: conf.Username, Password: conf.Password, }) @@ -94,3 +94,7 @@ func (c *mongoClient) GetDataStore(dbName string) Store { return mongoStore } + +func (c *mongoClient) HealthCheck(ctx context.Context) error { + return c.client.Ping(ctx, nil) +} diff --git a/db/mongo_test.go b/db/mongo_test.go new file mode 100644 index 0000000..a1e0aad --- /dev/null +++ b/db/mongo_test.go @@ -0,0 +1,32 @@ +// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved +// Author: Prabhjot Singh Sethi + +package db + +import ( + "context" + "testing" +) + +func Test_ClientConnection(t *testing.T) { + config := &MongoConfig{ + Host: "localhost", + Port: "27017", + Username: "root", + Password: "password", + } + + client, err := NewMongoClient(config) + + if err != nil { + t.Errorf("failed to connect to mongo DB Error: %s", err) + return + } + + err = client.HealthCheck(context.Background()) + if err != nil { + t.Errorf("failed to perform Health check with DB Error: %s", err) + } + + _ = client.GetDataStore("test") +} diff --git a/db/store.go b/db/store.go index 131ec0a..c498cb3 100644 --- a/db/store.go +++ b/db/store.go @@ -6,10 +6,20 @@ package db +import ( + "context" +) + type Store interface { } type StoreClient interface { // Get the Data Store interface given the client interface GetDataStore(dbName string) Store + + // Health Check, if the Store is connectable and healthy + // returns the status of health of the server by means of + // error if error is nil the health of the DB store can be + // considered healthy + HealthCheck(ctx context.Context) error }