Files
spsays-bff/internal/repository/mongo.go
T
2026-05-09 23:19:19 +05:30

55 lines
1.3 KiB
Go

package repository
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.uber.org/zap"
)
// MongoDB holds the MongoDB client and database reference.
type MongoDB struct {
Client *mongo.Client
DB *mongo.Database
logger *zap.Logger
}
// NewMongoDB connects to MongoDB and returns a MongoDB instance.
func NewMongoDB(uri, dbName string, logger *zap.Logger) (*MongoDB, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOpts := options.Client().ApplyURI(uri)
client, err := mongo.Connect(clientOpts)
if err != nil {
return nil, fmt.Errorf("mongo connect: %w", err)
}
if err := client.Ping(ctx, nil); err != nil {
return nil, fmt.Errorf("mongo ping: %w", err)
}
logger.Info("connected to MongoDB", zap.String("db", dbName))
return &MongoDB{
Client: client,
DB: client.Database(dbName),
logger: logger,
}, nil
}
// Close disconnects from MongoDB.
func (m *MongoDB) Close() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return m.Client.Disconnect(ctx)
}
// Collection returns a MongoDB collection handle.
func (m *MongoDB) Collection(name string) *mongo.Collection {
return m.DB.Collection(name)
}