Commit 73fdb3b7 authored by Max Richter's avatar Max Richter
Browse files

style(mongo): seperate utils funcs into two files

parent 1b5ce525
......@@ -2,9 +2,7 @@ package utils
import (
"context"
"flag"
"log"
"os"
"strings"
"time"
......@@ -12,37 +10,8 @@ import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
// Autoloads .env file
godotenv "github.com/joho/godotenv"
)
// GetEnv gets a env variable, and when not present returns the default value
func GetEnv(variableName string, defaultValue string) string {
godotenv.Load(".env")
envValue := os.Getenv(variableName)
if envValue == "" {
return defaultValue
}
return envValue
}
// GetDBName gets the db name from the environment
func GetDBName() string {
dbName := GetEnv("MONGO_DB", "good2go")
if flag.Lookup("test.v") == nil {
return dbName
}
return dbName + "_test"
}
// CreateDBClient creates a mongodb client and connects to the specified database
func CreateDBClient(timeout time.Duration) (client *mongo.Client, ctx context.Context) {
......@@ -53,7 +22,7 @@ func CreateDBClient(timeout time.Duration) (client *mongo.Client, ctx context.Co
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
ctx, cancel := CreateTimeoutCTX(timeout)
defer cancel()
err = client.Connect(ctx)
if err != nil {
......@@ -79,6 +48,7 @@ func CreateDBClient(timeout time.Duration) (client *mongo.Client, ctx context.Co
return client, ctx
}
func CreateTimoutCTX(timeout time.Duration) (context.Context, context.CancelFunc) {
// CreateTimeoutCTX creates a timeout context.
func CreateTimeoutCTX(timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), timeout)
}
package utils
import (
"flag"
"os"
godotenv "github.com/joho/godotenv"
)
// GetEnv gets a env variable, and when not present returns the default value
func GetEnv(variableName string, defaultValue string) string {
godotenv.Load(".env")
envValue := os.Getenv(variableName)
if envValue == "" {
return defaultValue
}
return envValue
}
// GetDBName gets the db name from the environment
func GetDBName() string {
dbName := GetEnv("MONGO_DB", "good2go")
if flag.Lookup("test.v") == nil {
return dbName
}
return dbName + "_test"
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment