centrelized collection creation logic
This commit is contained in:
33
dbhandler/mongo/connection.go
Normal file
33
dbhandler/mongo/connection.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.acooldomain.co/server-manager/backend/models"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func getMongoCollection(config models.MongoDBConfig) (*mongo.Collection, error) {
|
||||
clientOptions := options.Client().ApplyURI(config.Url)
|
||||
|
||||
if config.Username != "" || config.Password != "" {
|
||||
clientOptions = clientOptions.SetAuth(options.Credential{
|
||||
Username: config.Username,
|
||||
Password: config.Password,
|
||||
})
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeoutCause(context.Background(), 30*time.Second, fmt.Errorf("Timeout"))
|
||||
defer cancel()
|
||||
|
||||
client, err := mongo.Connect(ctx, clientOptions)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client.Database(config.Database).Collection(config.Collection), nil
|
||||
}
|
||||
Reference in New Issue
Block a user