Documentation
¶
Index ¶
- func NewMongoModule() fx.Option
- func UnwrapCollection(coll Collection) *mongodriver.Collection
- type Admin
- type Collection
- type Config
- type EntityMapper
- type GenericRepository
- 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]) FindByID(ctx context.Context, id string) (*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]) Update(ctx context.Context, domain *Domain) (*Domain, error)
- func (r *GenericRepository[Domain, Entity]) UpsertIfNewer(ctx context.Context, domain *Domain) (bool, error)
- type Middleware
- type Mongo
- type PageResult
- type QueryOptions
- type Session
- type WrapperOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewMongoModule ¶
func UnwrapCollection ¶
func UnwrapCollection(coll Collection) *mongodriver.Collection
UnwrapCollection unwraps a Collection to the underlying *mongo.Collection. This is useful when you need direct access to the driver's collection for operations not exposed through the Collection interface. Panics if the underlying collection is not *mongo.Collection (should never happen when using collections from Mongo.GetCollection/GetCollectionWithOptions).
Types ¶
type Admin ¶
type Admin interface {
Mongo
GetDatabase() *mongodriver.Database
StartSession(ctx context.Context) (Session, error)
}
Admin is the internal interface for infrastructure components (migrations, transactions).
type Collection ¶
type Collection interface {
FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongodriver.SingleResult
Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongodriver.Cursor, error)
InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongodriver.InsertOneResult, error)
InsertMany(ctx context.Context, documents []interface{}, opts ...*options.InsertManyOptions) (*mongodriver.InsertManyResult, error)
UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongodriver.UpdateResult, error)
UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongodriver.UpdateResult, error)
DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongodriver.DeleteResult, error)
DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongodriver.DeleteResult, error)
FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, opts ...*options.FindOneAndUpdateOptions) *mongodriver.SingleResult
FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongodriver.SingleResult
FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongodriver.SingleResult
Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*mongodriver.Cursor, error)
CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)
Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error)
ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.ReplaceOptions) (*mongodriver.UpdateResult, error)
BulkWrite(ctx context.Context, models []mongodriver.WriteModel, opts ...*options.BulkWriteOptions) (*mongodriver.BulkWriteResult, error)
Indexes() mongodriver.IndexView
Drop(ctx context.Context) error
Name() string
Database() *mongodriver.Database
}
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"` // Максимальний час виконання запиту до БД
}
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]( coll 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 ¶
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]) FindByID ¶
func (r *GenericRepository[Domain, Entity]) FindByID(ctx context.Context, id string) (*Domain, error)
FindByID retrieves an entity by ID.
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 Middleware ¶
Middleware represents a decorator that wraps context transformation for database operations. Middleware should only modify context (e.g., add timeout, tracing), not return errors.
type Mongo ¶
type Mongo interface {
GetCollection(collection string) Collection
GetCollectionWithOptions(collection string, opts ...WrapperOption) Collection
}
Mongo is the public interface for repository access.
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 Session ¶
type Session interface {
// StartTransaction starts a new transaction, configured with the given options, on this
// session. This method returns an error if there is already a transaction in-progress for this
// session.
StartTransaction(opts ...*options.TransactionOptions) error
// AbortTransaction aborts the active transaction for this session. This method returns an error
// if there is no active transaction for this session or if the transaction has been committed
// or aborted.
AbortTransaction(ctx context.Context) error
// CommitTransaction commits the active transaction for this session. This method returns an
// error if there is no active transaction for this session or if the transaction has been
// aborted.
CommitTransaction(ctx context.Context) error
// WithTransaction starts a transaction on this session and runs the fn callback. Errors with
// the TransientTransactionError and UnknownTransactionCommitResult labels are retried for up to
// 120 seconds. Inside the callback, the SessionContext must be used as the Context parameter
// for any operations that should be part of the transaction. If the ctx parameter already has a
// Session attached to it, it will be replaced by this session. The fn callback may be run
// multiple times during WithTransaction due to retry attempts, so it must be idempotent.
// Non-retryable operation errors or any operation errors that occur after the timeout expires
// will be returned without retrying. If the callback fails, the driver will call
// AbortTransaction.
WithTransaction(ctx context.Context, fn func(ctx mongodriver.SessionContext) (interface{}, error), opts ...*options.TransactionOptions) (interface{}, error)
// EndSession aborts any existing transactions and close the session.
EndSession(ctx context.Context)
// ClusterTime returns the current cluster time document associated with the session.
ClusterTime() bson.Raw
// OperationTime returns the current operation time document associated with the session.
OperationTime() *primitive.Timestamp
// Client returns the Client associated with the session.
Client() *mongodriver.Client
// ID returns the current ID document associated with the session. The ID document is in the
// form {"id": <BSON binary value>}.
ID() bson.Raw
// AdvanceClusterTime advances the cluster time for a session. This method returns an error if
// the session has ended.
AdvanceClusterTime(bson.Raw) error
// AdvanceOperationTime advances the operation time for a session. This method returns an error
// if the session has ended.
AdvanceOperationTime(*primitive.Timestamp) error
}
Session represents a MongoDB session for transaction support. This interface mirrors all public methods of mongo.Session to enable mocking. mongo.Session has unexported methods making it impossible to embed directly.
type WrapperOption ¶
type WrapperOption func(*wrapperOptions)
WrapperOption is a functional option for configuring CollectionWrapper.
func WithMiddleware ¶
func WithMiddleware(mw Middleware) WrapperOption
WithMiddleware adds a custom middleware to the wrapper.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) WrapperOption
WithTimeout adds timeout middleware to the wrapper.