Files
sxchnge/backend/shared/database/connection.go
T

42 lines
1.3 KiB
Go

package db
import (
"context"
mongoimpl "git.sendico.io/tech/sxchnge/shared/database/internal/mongo"
"git.sendico.io/tech/sxchnge/shared/database/source"
merrors "git.sendico.io/tech/sxchnge/shared/errors"
mlogger "git.sendico.io/tech/sxchnge/shared/logging"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)
type Connection interface {
Disconnect(context.Context) error
Ping(context.Context) error
}
type MongoConnection struct {
database source.Source
close func(context.Context) error
}
func (c *MongoConnection) Database() source.Source { return c.database }
func (c *MongoConnection) Disconnect(ctx context.Context) error { return c.close(ctx) }
func (c *MongoConnection) Ping(ctx context.Context) error {
database, ctx, release, err := c.database.Acquire(ctx)
if err != nil {
return err
}
defer release()
return database.Client().Ping(ctx, readpref.Primary())
}
func ConnectMongo(logger mlogger.Logger, config *Config) (*MongoConnection, error) {
if config == nil || config.Driver != Mongo {
return nil, merrors.InvalidArgument("MongoDB configuration is required")
}
database, close, err := mongoimpl.OpenSource(logger, config.Settings)
if err != nil {
return nil, err
}
return &MongoConnection{database: database, close: close}, nil
}