Documentation
¶
Index ¶
- Variables
- func MetricViews() []sdkmetric.View
- func NewMongoModule(opts ...Option) fx.Option
- func WithTransaction[T any](ctx context.Context, tm TxManager, fn func(txCtx context.Context) (T, error)) (T, error)
- type Admin
- type Config
- type EntityMapper
- type GenericRepository
- func NewGenericRepository[Domain any, Entity any](db Mongo, collectionName string, mapper EntityMapper[Domain, Entity]) (*GenericRepository[Domain, Entity], error)
- func NewTenantRepository[Domain any, Entity any](admin Admin, collectionName string, mapper EntityMapper[Domain, Entity]) (*GenericRepository[Domain, Entity], error)
- func (r *GenericRepository[Domain, Entity]) Collection(ctx context.Context) *mongodriver.Collection
- func (r *GenericRepository[Domain, Entity]) Delete(ctx context.Context, id string) error
- func (r *GenericRepository[Domain, Entity]) Exists(ctx context.Context, id string) (bool, error)
- func (r *GenericRepository[Domain, Entity]) ExistsWithFilter(ctx context.Context, filter bson.D) (bool, error)
- func (r *GenericRepository[Domain, Entity]) FindAll(ctx context.Context) ([]*Domain, error)
- func (r *GenericRepository[Domain, Entity]) FindAllWithFilter(ctx context.Context, filter bson.D, sort bson.D) ([]*Domain, error)
- func (r *GenericRepository[Domain, Entity]) FindByID(ctx context.Context, id string) (*Domain, error)
- func (r *GenericRepository[Domain, Entity]) FindOneByFilter(ctx context.Context, filter bson.D) (*Domain, error)
- func (r *GenericRepository[Domain, Entity]) FindWithOptions(ctx context.Context, opts QueryOptions) (*PageResult[Domain], error)
- func (r *GenericRepository[Domain, Entity]) Insert(ctx context.Context, domain *Domain) error
- func (r *GenericRepository[Domain, Entity]) Mapper() EntityMapper[Domain, Entity]
- func (r *GenericRepository[Domain, Entity]) Update(ctx context.Context, domain *Domain) (*Domain, error)
- func (r *GenericRepository[Domain, Entity]) UpsertIfNewer(ctx context.Context, domain *Domain) (bool, error)
- type MigrationConfig
- type Mongo
- type Option
- type PageResult
- type QueryOptions
- type TenantMigrationRunner
- type TenantSlugsProvider
- type TxManager
Constants ¶
This section is empty.
Variables ¶
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 MetricViews ¶ added in v0.5.8
MetricViews returns SDK views that reduce cardinality of otelmongo metrics.
Without these views, otelmongo generates high-cardinality series due to labels like network.peer.address, network.peer.port, db.namespace that provide little value but multiply series count significantly.
func NewMongoModule ¶
NewMongoModule provides MongoDB components for dependency injection. By default, configuration is loaded from koanf. 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 `koanf:"connection-string"`
Host string `koanf:"host"`
Port int `koanf:"port"`
ReplicaSet string `koanf:"replica-set"`
Username string `koanf:"username"`
Password string `koanf:"password"`
Database string `koanf:"database"`
DirectConnection bool `koanf:"direct-connection"`
// Connection Pool Settings
MaxPoolSize uint64 `koanf:"max-pool-size"` // Максимальна кількість з'єднань у пулі
MinPoolSize uint64 `koanf:"min-pool-size"` // Мінімальна кількість з'єднань у пулі
MaxConnIdleTime time.Duration `koanf:"max-conn-idle-time"` // Час простою з'єднання перед закриттям
ConnectTimeout time.Duration `koanf:"connect-timeout"` // Таймаут підключення
ServerSelectTimeout time.Duration `koanf:"server-select-timeout"` // Таймаут вибору сервера
// Query Timeout Settings
QueryTimeout time.Duration `koanf:"query-timeout"` // Максимальний час виконання запиту до БД
// Migration Settings
Migrations MigrationConfig `koanf:"migrations"`
}
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 ¶
GenericRepository provides common CRUD operations for MongoDB.
func NewGenericRepository ¶
func NewGenericRepository[Domain any, Entity any]( db Mongo, collectionName string, mapper EntityMapper[Domain, Entity], ) (*GenericRepository[Domain, Entity], error)
NewGenericRepository creates a new generic repository with a fixed collection. This is the standard constructor for single-tenant services.
func NewTenantRepository ¶ added in v0.6.4
func NewTenantRepository[Domain any, Entity any]( admin Admin, collectionName string, mapper EntityMapper[Domain, Entity], ) (*GenericRepository[Domain, Entity], error)
NewTenantRepository creates a new generic repository with tenant-aware collection resolution. Used for multi-tenant services where the collection is resolved per-request based on the tenant slug in the context (database-per-tenant strategy).
func (*GenericRepository[Domain, Entity]) Collection ¶ added in v0.6.0
func (r *GenericRepository[Domain, Entity]) Collection(ctx context.Context) *mongodriver.Collection
Collection resolves the MongoDB collection for the current request context. Use this in custom repository methods that need raw collection access.
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 ¶
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]) Mapper ¶ added in v0.6.0
func (r *GenericRepository[Domain, Entity]) Mapper() EntityMapper[Domain, Entity]
Mapper returns the entity mapper used by this repository.
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 MigrationConfig ¶ added in v0.4.6
type MigrationConfig struct {
// Disabled controls whether migrations are skipped on startup
Disabled bool `koanf:"disabled"`
// Path to migrations directory
Path string `koanf:"path"`
}
MigrationConfig holds migration-specific configuration.
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
WithMongoConfig provides a static Config (useful for tests).
func WithTenantMigrations ¶ added in v0.6.4
func WithTenantMigrations() Option
WithTenantMigrations enables per-tenant database migrations. When set, TenantSlugsProvider must be provided in the fx container. The provider fetches tenant slugs at startup, and migrations run against each tenant database ({database}_{slug}).
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 TenantMigrationRunner ¶ added in v0.6.6
TenantMigrationRunner runs migrations for a single tenant database on demand. Used by Kafka consumer handlers when a new tenant is created.
type TenantSlugsProvider ¶ added in v0.6.4
TenantSlugsProvider fetches the list of active tenant slugs at startup. Implementations typically call tenant-service API.