codeword/internal/initialize/mongo.go

51 lines
1.1 KiB
Go
Raw Normal View History

2023-12-29 12:41:26 +00:00
package initialize
import (
2024-01-15 13:32:46 +00:00
"codeword/internal/repository"
2023-12-29 12:41:26 +00:00
mdb "codeword/pkg/mongo"
"context"
"go.mongodb.org/mongo-driver/mongo"
2024-01-15 13:32:46 +00:00
"go.uber.org/zap"
2023-12-29 12:41:26 +00:00
"time"
)
2024-01-11 12:07:17 +00:00
func MongoDB(ctx context.Context, cfg Config) (*mongo.Database, error) {
2023-12-29 12:41:26 +00:00
dbConfig := &mdb.Configuration{
MongoHost: cfg.MongoHost,
MongoPort: cfg.MongoPort,
MongoUser: cfg.MongoUser,
MongoPassword: cfg.MongoPassword,
MongoDatabase: cfg.MongoDatabase,
MongoAuth: cfg.MongoAuth,
}
2024-01-15 13:32:46 +00:00
newCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
2024-01-15 08:43:55 +00:00
defer cancel()
2023-12-29 12:41:26 +00:00
mongoDeps := &mdb.ConnectDeps{
Configuration: dbConfig,
Timeout: 10 * time.Second,
}
2024-01-15 13:32:46 +00:00
db, err := mdb.Connect(newCtx, mongoDeps)
2023-12-29 12:41:26 +00:00
if err != nil {
return nil, err
}
2024-01-15 13:32:46 +00:00
err = db.Client().Ping(newCtx, nil)
2023-12-29 12:41:26 +00:00
if err != nil {
return nil, err
}
return db, nil
}
2024-01-15 13:32:46 +00:00
func InitDatabaseIndexes(ctx context.Context, mdb *mongo.Database, logger *zap.Logger) error {
if err := repository.InitPromoCodeIndexes(ctx, mdb.Collection("promoCodes")); err != nil {
logger.Error("Failed to initialize promoCodes indexes", zap.Error(err))
return err
}
return nil
}