You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mongox-go-driver/mongox-testing/database/ephemeral.go

56 lines
1.3 KiB

package database
4 years ago
import (
"context"
"os"
4 years ago
"go.mongodb.org/mongo-driver/bson/primitive"
4 years ago
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
4 years ago
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/mainnika/mongox-go-driver/v2/mongox/database"
4 years ago
)
// 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 {
4 years ago
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) {
11 months ago
return NewEphemeralWithContext(context.Background(), URI)
}
4 years ago
11 months ago
func NewEphemeralWithContext(ctx context.Context, URI string) (db *EphemeralDatabase, err error) {
if URI == "" {
URI = defaultURI
}
name := primitive.NewObjectID().Hex()
4 years ago
opts := options.Client().ApplyURI(URI)
11 months ago
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, err
}
4 years ago
11 months ago
db = &EphemeralDatabase{Database: database.NewDatabase(ctx, client, name)}
4 years ago
11 months ago
return db, nil
4 years ago
}
// Close the connection and drop database
func (e *EphemeralDatabase) Close() (err error) {
return e.Client().Database(e.Name()).Drop(e.Context())
4 years ago
}