heruvym/internal/initialize/mongo.go

26 lines
657 B
Go
Raw Normal View History

2024-09-25 14:22:57 +00:00
package initialize
import (
"context"
2024-10-01 11:34:09 +00:00
"fmt"
2024-09-25 14:22:57 +00:00
"go.mongodb.org/mongo-driver/mongo"
2024-10-01 11:34:09 +00:00
"go.mongodb.org/mongo-driver/mongo/options"
2024-09-25 14:22:57 +00:00
"time"
)
func MongoDB(ctx context.Context, cfg Config) (*mongo.Database, error) {
newCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
2024-10-01 11:34:09 +00:00
clientOptions := options.Client().ApplyURI(cfg.MongoURI)
client, err := mongo.Connect(newCtx, clientOptions)
2024-09-25 14:22:57 +00:00
if err != nil {
2024-10-01 11:34:09 +00:00
return nil, fmt.Errorf("failed to connect to MongoDB: %w", err)
2024-09-25 14:22:57 +00:00
}
2024-10-01 11:34:09 +00:00
err = client.Ping(newCtx, nil)
2024-09-25 14:22:57 +00:00
if err != nil {
2024-10-01 11:34:09 +00:00
return nil, fmt.Errorf("failed to ping MongoDB: %w", err)
2024-09-25 14:22:57 +00:00
}
2024-10-01 11:34:09 +00:00
db := client.Database(cfg.MongoDbTable)
2024-09-25 14:22:57 +00:00
return db, nil
}