mongo

package
v0.4.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEntityNotFound is returned when an entity is not found in the repository.
	ErrEntityNotFound = errors.New("entity not found")

	// ErrOptimisticLocking is returned when an optimistic locking conflict occurs.
	ErrOptimisticLocking = errors.New("optimistic locking error")
)

Functions

func NewMongoModule

func NewMongoModule(opts ...Option) fx.Option

NewMongoModule provides MongoDB components for dependency injection. By default, configuration is loaded from viper. Use WithMongoConfig for static config (useful for tests).

func WithTransaction added in v0.4.3

func WithTransaction[T any](ctx context.Context, tm TxManager, fn func(txCtx context.Context) (T, error)) (T, error)

WithTransaction is a generic wrapper around TxManager.WithTransaction that provides type-safe transaction handling without manual type assertions.

Types

type Admin

type Admin interface {
	Mongo
	GetDatabase() *mongodriver.Database
	StartSession(ctx context.Context) (*mongodriver.Session, error)
}

Admin is the internal interface for infrastructure components (migrations, transactions).

type Config

type Config struct {
	ConnectionString string `mapstructure:"connection-string"`
	Host             string `mapstructure:"host"`
	Port             int    `mapstructure:"port"`
	ReplicaSet       string `mapstructure:"replica-set"`
	Username         string `mapstructure:"username"`
	Password         string `mapstructure:"password"`
	Database         string `mapstructure:"database"`
	DirectConnection bool   `mapstructure:"direct-connection"`

	// Connection Pool Settings
	MaxPoolSize         uint64        `mapstructure:"max-pool-size"`         // Максимальна кількість з'єднань у пулі
	MinPoolSize         uint64        `mapstructure:"min-pool-size"`         // Мінімальна кількість з'єднань у пулі
	MaxConnIdleTime     time.Duration `mapstructure:"max-conn-idle-time"`    // Час простою з'єднання перед закриттям
	ConnectTimeout      time.Duration `mapstructure:"connect-timeout"`       // Таймаут підключення
	ServerSelectTimeout time.Duration `mapstructure:"server-select-timeout"` // Таймаут вибору сервера

	// Query Timeout Settings
	QueryTimeout time.Duration `mapstructure:"query-timeout"` // Максимальний час виконання запиту до БД
}

Config holds the MongoDB connection configuration.

type EntityMapper

type EntityMapper[Domain any, Entity any] interface {
	// ToEntity converts domain model to MongoDB entity
	ToEntity(domain *Domain) *Entity

	// ToDomain converts MongoDB entity to domain model
	ToDomain(entity *Entity) *Domain

	// GetID extracts ID from entity (for queries)
	GetID(entity *Entity) string

	// GetVersion extracts version from entity (for optimistic locking)
	GetVersion(entity *Entity) int

	// SetVersion sets version on entity (for optimistic locking)
	SetVersion(entity *Entity, version int)
}

EntityMapper defines the contract for converting between domain models and MongoDB entities. Each repository implementation must provide this mapper.

type GenericRepository

type GenericRepository[Domain any, Entity any] struct {
	// contains filtered or unexported fields
}

GenericRepository provides common CRUD operations for MongoDB.

func NewGenericRepository

func NewGenericRepository[Domain any, Entity any](
	coll *mongodriver.Collection,
	mapper EntityMapper[Domain, Entity],
) (*GenericRepository[Domain, Entity], error)

NewGenericRepository creates a new generic repository. Returns error if collection or mapper is nil.

func (*GenericRepository[Domain, Entity]) Delete

func (r *GenericRepository[Domain, Entity]) Delete(ctx context.Context, id string) error

Delete hard deletes an entity by ID.

func (*GenericRepository[Domain, Entity]) Exists

func (r *GenericRepository[Domain, Entity]) Exists(ctx context.Context, id string) (bool, error)

Exists checks if an entity with the given ID exists.

func (*GenericRepository[Domain, Entity]) ExistsWithFilter

func (r *GenericRepository[Domain, Entity]) ExistsWithFilter(ctx context.Context, filter bson.D) (bool, error)

ExistsWithFilter checks if any entity matching the filter exists.

func (*GenericRepository[Domain, Entity]) FindAll

func (r *GenericRepository[Domain, Entity]) FindAll(ctx context.Context) ([]*Domain, error)

FindAll retrieves all entities.

func (*GenericRepository[Domain, Entity]) FindAllWithFilter added in v0.2.7

func (r *GenericRepository[Domain, Entity]) FindAllWithFilter(
	ctx context.Context,
	filter bson.D,
	sort bson.D,
) ([]*Domain, error)

FindAllWithFilter retrieves all entities matching the filter with optional sorting (no pagination).

func (*GenericRepository[Domain, Entity]) FindByID

func (r *GenericRepository[Domain, Entity]) FindByID(ctx context.Context, id string) (*Domain, error)

FindByID retrieves an entity by ID.

func (*GenericRepository[Domain, Entity]) FindOneByFilter added in v0.2.7

func (r *GenericRepository[Domain, Entity]) FindOneByFilter(ctx context.Context, filter bson.D) (*Domain, error)

FindOneByFilter retrieves a single entity matching the filter.

func (*GenericRepository[Domain, Entity]) FindWithOptions

func (r *GenericRepository[Domain, Entity]) FindWithOptions(
	ctx context.Context,
	opts QueryOptions,
) (*PageResult[Domain], error)

FindWithOptions retrieves entities with filtering, pagination and sorting.

func (*GenericRepository[Domain, Entity]) Insert

func (r *GenericRepository[Domain, Entity]) Insert(ctx context.Context, domain *Domain) error

Insert creates a new entity in MongoDB.

func (*GenericRepository[Domain, Entity]) Update

func (r *GenericRepository[Domain, Entity]) Update(ctx context.Context, domain *Domain) (*Domain, error)

Update updates an existing entity with optimistic locking and returns the updated domain object.

func (*GenericRepository[Domain, Entity]) UpsertIfNewer

func (r *GenericRepository[Domain, Entity]) UpsertIfNewer(ctx context.Context, domain *Domain) (bool, error)

UpsertIfNewer inserts or replaces an entity only if its version is greater than the existing one. This is useful for CQRS projections where events may arrive out of order. Returns true if the entity was inserted/updated, false if skipped due to version conflict.

type Mongo

type Mongo interface {
	GetCollection(collection string) *mongodriver.Collection
}

Mongo is the public interface for repository access.

type Option added in v0.4.3

type Option func(*mongoOptions)

Option is a functional option for configuring the Mongo module.

func WithMongoConfig added in v0.4.3

func WithMongoConfig(cfg Config) Option

WithMongoConfig provides a static Config (useful for tests).

type PageResult

type PageResult[Domain any] struct {
	// Items is the list of domain objects for the current page
	Items []*Domain
	// Total is the total number of items matching the filter
	Total int64
	// Page is the current page number (1-based)
	Page int
	// Size is the number of items per page
	Size int
	// TotalPages is the total number of pages
	TotalPages int
}

PageResult represents a paginated result.

type QueryOptions

type QueryOptions struct {
	// Filter is the MongoDB filter criteria (BSON)
	Filter bson.D
	// Page is the page number (1-based)
	Page int
	// Size is the number of items per page
	Size int
	// Sort is the MongoDB sort criteria (BSON)
	// Example: bson.D{{"createdAt", -1}} for descending order
	Sort bson.D
}

QueryOptions defines options for querying entities with filtering, pagination and sorting.

type TxManager added in v0.4.3

type TxManager interface {
	WithTransaction(ctx context.Context, fn func(txCtx context.Context) (any, error)) (any, error)
}

TxManager defines the interface for transaction management.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL