mirror of
https://github.com/mainnika/mongox-go-driver.git
synced 2026-05-22 15:53:36 +00:00
Override default ephemeral database uri by using env variable
This commit is contained in:
@@ -2,6 +2,7 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
@@ -11,14 +12,28 @@ import (
|
||||
"github.com/mainnika/mongox-go-driver/v2/mongox/database"
|
||||
)
|
||||
|
||||
// defaultURI is a mongodb uri that is being used by tests
|
||||
var defaultURI = "mongodb://localhost"
|
||||
|
||||
// EphemeralDatabase is a temporary database connection that will be destroyed after close
|
||||
type EphemeralDatabase struct {
|
||||
mongox.Database
|
||||
}
|
||||
|
||||
func init() {
|
||||
envURI := os.Getenv("MONGODB_URI")
|
||||
if envURI != "" {
|
||||
defaultURI = envURI
|
||||
}
|
||||
}
|
||||
|
||||
// NewEphemeral creates new mongo connection
|
||||
func NewEphemeral(URI string) (db *EphemeralDatabase, err error) {
|
||||
|
||||
if URI == "" {
|
||||
URI = defaultURI
|
||||
}
|
||||
|
||||
name := primitive.NewObjectID().Hex()
|
||||
opts := options.Client().ApplyURI(URI)
|
||||
client, err := mongo.Connect(context.Background(), opts)
|
||||
|
||||
@@ -41,7 +41,7 @@ func Test_SaveLoad(t *testing.T) {
|
||||
Primary `bson:",inline" json:",inline" collection:"1"`
|
||||
}
|
||||
|
||||
db, err := database.NewEphemeral("mongodb://localhost")
|
||||
db, err := database.NewEphemeral("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func Test_SaveLoad(t *testing.T) {
|
||||
Primary `bson:",inline" json:",inline" collection:"1"`
|
||||
}
|
||||
|
||||
db, err := database.NewEphemeral("mongodb://localhost")
|
||||
db, err := database.NewEphemeral("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func Test_SaveLoad(t *testing.T) {
|
||||
Primary `bson:",inline" json:",inline" collection:"1"`
|
||||
}
|
||||
|
||||
db, err := database.NewEphemeral("mongodb://localhost")
|
||||
db, err := database.NewEphemeral("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
func TestDatabase_Ensure(t *testing.T) {
|
||||
|
||||
db, err := database.NewEphemeral("mongodb://localhost")
|
||||
db, err := database.NewEphemeral("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user