centrelized collection creation logic

This commit is contained in:
2025-03-19 13:27:43 +02:00
parent 946bd6018f
commit ba47810398
4 changed files with 39 additions and 39 deletions

View 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
}