This commit is contained in:
Kar
2024-01-08 14:00:41 +05:30
commit dbe86acfac
31 changed files with 1793 additions and 0 deletions

View File

@@ -0,0 +1,239 @@
package mongomanager
import (
"gitlab.com/arkadooti.sarkar/go-boilerplate/core/appcontext"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func (client *mongoService) Disconnect(ctx appcontext.AppContext) error {
return client.DB.Disconnect(ctx)
}
func (client *mongoService) CreateOne(ctx appcontext.AppContext, database, collectionName string, d interface{}) (*mongo.InsertOneResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
insertOneResult, err := collection.InsertOne(ctx.Context, d)
if err != nil {
return nil, err
}
return insertOneResult, nil
}
// CreateMany - inserts many data into mongo database
func (client *mongoService) CreateMany(ctx appcontext.AppContext, database, collectionName string, d []interface{}) (*mongo.InsertManyResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
insertManyRslt, err := collection.InsertMany(ctx.Context, d)
if err != nil {
return nil, err
}
return insertManyRslt, nil
}
// ReadOne - reads single document from mongo database
func (client *mongoService) ReadOne(ctx appcontext.AppContext, database, collectionName string, filter, data interface{}) error {
collection := client.DB.Database(database).Collection(collectionName)
err := collection.FindOne(ctx.Context, filter).Decode(data)
if err != nil {
return err
}
return nil
}
// ReadAll - reads multiple documents from mongo database
func (client *mongoService) ReadAll(ctx appcontext.AppContext, database, collectionName string, filter, data interface{}, opts ...*options.FindOptions) error {
var findOptions *options.FindOptions
if len(opts) > 0 {
findOptions = opts[0]
}
collection := client.DB.Database(database).Collection(collectionName)
cursor, err := collection.Find(ctx.Context, filter, findOptions)
if err != nil {
return err
}
defer cursor.Close(ctx.Context)
err = cursor.All(ctx.Context, data)
if err != nil {
return err
}
return nil
}
// Update - updates data into mongo database
func (client *mongoService) Update(ctx appcontext.AppContext, database, collectionName string, filter, update interface{}, options ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
updateResult, err := collection.UpdateOne(ctx.Context, filter, update, options...)
if err != nil {
return nil, err
}
return updateResult, nil
}
// ReplaceOne - replace one document into mongo database
func (client *mongoService) ReplaceOne(ctx appcontext.AppContext, database, collectionName string, filter, replacement interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
updateResult, err := collection.ReplaceOne(ctx.Context, filter, replacement, opts...)
if err != nil {
return nil, err
}
return updateResult, nil
}
// UpdateAndReturn - updates data into mongo database and returns the updated document
func (client *mongoService) UpdateAndReturn(ctx appcontext.AppContext, database, collectionName string, filter, update, data interface{}) error {
collection := client.DB.Database(database).Collection(collectionName)
after := options.After
opts := options.FindOneAndUpdateOptions{
ReturnDocument: &after,
}
err := collection.FindOneAndUpdate(ctx.Context, filter, update, &opts).Decode(data)
if err != nil {
return err
}
return nil
}
// UpdateAll - updates multiple documents into mongo database
func (client *mongoService) UpdateAll(ctx appcontext.AppContext, database, collectionName string, filter, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
updateResult, err := collection.UpdateMany(ctx.Context, filter, update, opts...)
if err != nil {
return nil, err
}
return updateResult, nil
}
func (client *mongoService) Upsert(ctx appcontext.AppContext, database, collectionName string, filter,
update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
updateOptions := options.Update()
if len(opts) >= 1 {
updateOptions = opts[0]
}
updateOptions.SetUpsert(true)
updateResult, err := collection.UpdateOne(ctx.Context, filter, update, updateOptions)
if err != nil {
return nil, err
}
return updateResult, nil
}
// Delete - removes single doc data from the database
func (client *mongoService) Delete(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (*mongo.DeleteResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
deleteResult, err := collection.DeleteOne(ctx.Context, filter)
if err != nil {
return nil, err
}
return deleteResult, nil
}
// DeleteAll - removes all doc data from the database
func (client *mongoService) DeleteAll(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (*mongo.DeleteResult, error) {
collection := client.DB.Database(database).Collection(collectionName)
deleteResult, err := collection.DeleteMany(ctx.Context, filter)
if err != nil {
return nil, err
}
return deleteResult, nil
}
// CountDocuments returns document count of a collection
func (client *mongoService) CountDocuments(ctx appcontext.AppContext, database, collectionName string, filter interface{}, opts ...*options.CountOptions) (int64, error) {
var countOptions *options.CountOptions
if len(opts) > 0 {
countOptions = opts[0]
}
collection := client.DB.Database(database).Collection(collectionName)
count, err := collection.CountDocuments(ctx.Context, filter, countOptions)
if err != nil {
return 0, err
}
return count, nil
}
// Exist verifies if document is present or not
// if it returns error then there is a connection error else boolean value specifies whether doc is present or not
func (client *mongoService) Exist(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (bool, error) {
var i interface{}
collection := client.DB.Database(database).Collection(collectionName)
err := collection.FindOne(ctx.Context, filter).Decode(&i)
if err != nil {
return false, nil
}
return true, nil
}
// GetDistinct gets the distinct values for the field name provided
func (client *mongoService) GetDistinct(ctx appcontext.AppContext, database, collectionName, fieldName string, filter interface{}) (interface{}, error) {
collection := client.DB.Database(database).Collection(collectionName)
result, err := collection.Distinct(ctx.Context, fieldName, filter, nil)
if err != nil {
return nil, err
}
return result, nil
}
// AggregateAll executes aggregation query on a collection
// query []bson.M, data is a pointer to an array
func (client *mongoService) AggregateAll(ctx appcontext.AppContext, database, collectionName string, query, data interface{}, options ...*options.AggregateOptions) error {
collection := client.DB.Database(database).Collection(collectionName)
cursor, err := collection.Aggregate(ctx.Context, query, options...)
if err != nil {
return err
}
err = cursor.All(ctx.Context, data)
return err
}
// FindOneAndUpdate executes a findAndModify command to update at most one document in the collection and returns the
// document as it appeared before updating.
func (client *mongoService) FindOneAndUpdate(ctx appcontext.AppContext, database, collectionName string, filter, update, data interface{},
opts ...*options.FindOneAndUpdateOptions) error {
after := options.After
option := &options.FindOneAndUpdateOptions{
ReturnDocument: &after,
}
if len(opts) > 0 {
option = opts[0]
}
collection := client.DB.Database(database).Collection(collectionName)
result := collection.FindOneAndUpdate(ctx.Context, filter, update, option)
if result.Err() != nil {
return result.Err()
}
decodeErr := result.Decode(data)
if decodeErr != nil {
return decodeErr
}
return nil
}
func (client *mongoService) BulkWrite(ctx appcontext.AppContext, database, collectionName string, operations []mongo.WriteModel, bulkOption *options.BulkWriteOptions) (*mongo.BulkWriteResult, error) {
var err error
collection := client.DB.Database(database).Collection(collectionName)
result, err := collection.BulkWrite(ctx.Context, operations, bulkOption)
if err != nil {
return nil, err
}
return result, nil
}

View File

@@ -0,0 +1,89 @@
package mongomanager
import (
"context"
"errors"
"gitlab.com/arkadooti.sarkar/go-boilerplate/core/appcontext"
"gitlab.com/arkadooti.sarkar/go-boilerplate/core/log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
type mongoService struct {
DB *mongo.Client
}
type MongoDB interface {
Disconnect(ctx appcontext.AppContext) error
CreateOne(ctx appcontext.AppContext, database, collectionName string, d interface{}) (*mongo.InsertOneResult, error)
CreateMany(ctx appcontext.AppContext, database, collectionName string, d []interface{}) (*mongo.InsertManyResult, error)
ReadOne(ctx appcontext.AppContext, database, collectionName string, filter, data interface{}) error
ReadAll(ctx appcontext.AppContext, database, collectionName string, filter, data interface{}, opts ...*options.FindOptions) error
Update(ctx appcontext.AppContext, database, collectionName string, filter, update interface{}, options ...*options.UpdateOptions) (*mongo.UpdateResult, error)
ReplaceOne(ctx appcontext.AppContext, database, collectionName string, filter, replacement interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)
Upsert(ctx appcontext.AppContext, database, collectionName string, filter, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
UpdateAndReturn(ctx appcontext.AppContext, database, collectionName string, filter, update, data interface{}) error
UpdateAll(ctx appcontext.AppContext, database, collectionName string, filter, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
Delete(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (*mongo.DeleteResult, error)
DeleteAll(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (*mongo.DeleteResult, error)
CountDocuments(ctx appcontext.AppContext, database, collectionName string, filter interface{}, opts ...*options.CountOptions) (int64, error)
Exist(ctx appcontext.AppContext, database, collectionName string, filter interface{}) (bool, error)
GetDistinct(ctx appcontext.AppContext, database, collectionName, fieldName string, filter interface{}) (interface{}, error)
AggregateAll(ctx appcontext.AppContext, database, collectionName string, query, data interface{}, options ...*options.AggregateOptions) error
FindOneAndUpdate(ctx appcontext.AppContext, database, collectionName string, filter, update, data interface{}, opts ...*options.FindOneAndUpdateOptions) error
BulkWrite(ctx appcontext.AppContext, database, collectionName string, operations []mongo.WriteModel, bulkOption *options.BulkWriteOptions) (*mongo.BulkWriteResult, error)
}
func NewMongoClient(url, appName string) (MongoDB, error) {
ctx := appcontext.NewAppContext()
client, err := connect(url, appName)
if err != nil {
log.GenericError(ctx, errors.New("can't connect to db: "+err.Error()), nil)
return &mongoService{DB: client}, err
}
return &mongoService{DB: client}, nil
}
func connect(host, appName string) (*mongo.Client, error) {
var client *mongo.Client
servSelecTimeout := time.Duration(15) * time.Second
connTimeout := time.Duration(10) * time.Second
idleTime := time.Duration(2) * time.Minute
socketTimeout := time.Duration(2) * time.Minute
maxPooling := uint64(100)
clientOptions := &options.ClientOptions{
AppName: &appName,
ServerSelectionTimeout: &servSelecTimeout,
ConnectTimeout: &connTimeout,
MaxConnIdleTime: &idleTime,
MaxPoolSize: &maxPooling,
SocketTimeout: &socketTimeout,
}
clientOptions = clientOptions.ApplyURI(host)
err := clientOptions.Validate()
if err != nil {
return client, err
}
client, err = mongo.NewClient(clientOptions)
if err != nil {
return client, err
}
err = client.Connect(context.TODO())
if err != nil {
return client, err
}
err = client.Ping(context.TODO(), nil)
if err != nil {
return client, err
}
return client, nil
}