Skip to content

Commit

Permalink
Create connection.go
Browse files Browse the repository at this point in the history
  • Loading branch information
Adarshkumar14 authored Feb 22, 2022
1 parent 8245977 commit 2788ab0
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions pkg/database/connection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package database

import (
"context"
"errors"
"fmt"
"os"
"time"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

const (
ConnectionTimeout = 20 * time.Second
)

// Connect creates a new database client with the current configuration
func Connect() (*mongo.Client, error) {
var (
dbServer = os.Getenv("DB_SERVER")
dbUser = os.Getenv("DB_USER")
dbPassword = os.Getenv("DB_PASSWORD")
)

if dbServer == "" || dbUser == "" || dbPassword == "" {
return nil, errors.New("missing database configuration")
}

credential := options.Credential{
Username: dbUser,
Password: dbPassword,
}

clientOptions := options.Client().ApplyURI(dbServer).SetAuth(credential)
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
return nil, fmt.Errorf("failed to connect to db, error=%w", err)
}

ctx, cancel := context.WithTimeout(context.Background(), ConnectionTimeout)
defer cancel()

// Check the connection
err = client.Ping(ctx, nil)
if err != nil {
return nil, fmt.Errorf("failed to ping db, error=%w", err)
}

return client, nil
}

0 comments on commit 2788ab0

Please sign in to comment.