Refactor user domain to utilize string IDs and integrate MongoDB ORM

- Updated User entity to embed MongoDB model and replace uuid.UUID with string for ID fields.
- Modified repository methods to accept string IDs instead of uuid.UUID, enhancing compatibility with MongoDB.
- Refactored service and handler methods to align with the new ID type, ensuring consistent usage across the user management functionality.
- Improved response handling in UserListResponse to directly use string IDs.
- Streamlined index creation in the user repository using the MongoDB ORM for better maintainability.
This commit is contained in:
n.nakhostin
2025-08-11 13:45:46 +03:30
parent 8c1e593686
commit 08cf927294
6 changed files with 252 additions and 355 deletions
+129 -207
View File
@@ -7,104 +7,58 @@ import (
"tm/pkg/logger"
mongopkg "tm/pkg/mongo"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Repository defines methods for user data access
type Repository interface {
Create(ctx context.Context, user *User) error
GetByID(ctx context.Context, id uuid.UUID) (*User, error)
GetByID(ctx context.Context, id string) (*User, error)
GetByEmail(ctx context.Context, email string) (*User, error)
GetByUsername(ctx context.Context, username string) (*User, error)
Update(ctx context.Context, user *User) error
Delete(ctx context.Context, id uuid.UUID) error
Delete(ctx context.Context, id string) error
List(ctx context.Context, limit, offset int) ([]*User, error)
Search(ctx context.Context, search string, status *string, role *string, companyID *uuid.UUID, limit, offset int, sortBy, sortOrder string) ([]*User, error)
GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, error)
Search(ctx context.Context, search string, status *string, role *string, companyID *string, limit, offset int, sortBy, sortOrder string) ([]*User, error)
GetByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*User, error)
GetByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error)
UpdateLastLogin(ctx context.Context, id uuid.UUID) error
CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error)
UpdateLastLogin(ctx context.Context, id string) error
CountByCompanyID(ctx context.Context, companyID string) (int64, error)
}
// userRepository implements the Repository interface
// userRepository implements the Repository interface using the MongoDB ORM
type userRepository struct {
collection *mongo.Collection
logger logger.Logger
ormRepo mongopkg.Repository[User]
logger logger.Logger
}
// NewUserRepository creates a new user repository
func NewUserRepository(mongoManager *mongopkg.ConnectionManager, logger logger.Logger) Repository {
collection := mongoManager.GetCollection("users")
// Create indexes using the ORM's index management
indexes := []mongopkg.Index{
*mongopkg.CreateUniqueIndex("email_idx", bson.D{{Key: "email", Value: 1}}),
*mongopkg.CreateUniqueIndex("username_idx", bson.D{{Key: "username", Value: 1}}),
*mongopkg.NewIndex("company_id_idx", bson.D{{Key: "company_id", Value: 1}}),
*mongopkg.NewIndex("role_idx", bson.D{{Key: "role", Value: 1}}),
*mongopkg.NewIndex("status_idx", bson.D{{Key: "status", Value: 1}}),
*mongopkg.NewIndex("created_at_idx", bson.D{{Key: "created_at", Value: -1}}),
*mongopkg.CreateTextIndex("search_idx", "full_name", "email", "username", "department", "position"),
}
// Create indexes
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Email index (unique)
emailIndex := mongo.IndexModel{
Keys: bson.D{{Key: "email", Value: 1}},
Options: options.Index().SetUnique(true),
}
// Username index (unique)
usernameIndex := mongo.IndexModel{
Keys: bson.D{{Key: "username", Value: 1}},
Options: options.Index().SetUnique(true),
}
// Company ID index
companyIndex := mongo.IndexModel{
Keys: bson.D{{Key: "company_id", Value: 1}},
}
// Role index
roleIndex := mongo.IndexModel{
Keys: bson.D{{Key: "role", Value: 1}},
}
// Status index
statusIndex := mongo.IndexModel{
Keys: bson.D{{Key: "status", Value: 1}},
}
// Created at index
createdAtIndex := mongo.IndexModel{
Keys: bson.D{{Key: "created_at", Value: -1}},
}
// Full text search index
textIndex := mongo.IndexModel{
Keys: bson.D{
{Key: "full_name", Value: "text"},
{Key: "email", Value: "text"},
{Key: "username", Value: "text"},
{Key: "department", Value: "text"},
{Key: "position", Value: "text"},
},
}
_, err := collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
emailIndex,
usernameIndex,
companyIndex,
roleIndex,
statusIndex,
createdAtIndex,
textIndex,
})
err := mongoManager.CreateIndexes("users", indexes)
if err != nil {
logger.Warn("Failed to create user indexes", map[string]interface{}{
"error": err.Error(),
})
}
// Create ORM repository
ormRepo := mongopkg.NewRepository[User](mongoManager.GetCollection("users"), logger)
return &userRepository{
collection: collection,
logger: logger,
ormRepo: ormRepo,
logger: logger,
}
}
@@ -112,25 +66,22 @@ func NewUserRepository(mongoManager *mongopkg.ConnectionManager, logger logger.L
func (r *userRepository) Create(ctx context.Context, user *User) error {
// Set created/updated timestamps using Unix timestamps
now := time.Now().Unix()
user.CreatedAt = now
user.UpdatedAt = now
user.SetCreatedAt(now)
user.SetUpdatedAt(now)
// Insert user
_, err := r.collection.InsertOne(ctx, user)
// Use ORM to create user
err := r.ormRepo.Create(ctx, user)
if err != nil {
if mongo.IsDuplicateKeyError(err) {
return errors.New("user already exists")
}
r.logger.Error("Failed to create user", map[string]interface{}{
"error": err.Error(),
"email": user.Email,
"user_id": user.ID.String(),
"user_id": user.ID,
})
return err
}
r.logger.Info("User created successfully", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
"role": user.Role,
})
@@ -139,35 +90,28 @@ func (r *userRepository) Create(ctx context.Context, user *User) error {
}
// GetByID retrieves a user by ID
func (r *userRepository) GetByID(ctx context.Context, id uuid.UUID) (*User, error) {
var user User
filter := bson.M{"_id": id}
err := r.collection.FindOne(ctx, filter).Decode(&user)
func (r *userRepository) GetByID(ctx context.Context, id string) (*User, error) {
user, err := r.ormRepo.FindByID(ctx, id)
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
return nil, errors.New("user not found")
}
r.logger.Error("Failed to get user by ID", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
})
return nil, err
}
return &user, nil
return user, nil
}
// GetByEmail retrieves a user by email
func (r *userRepository) GetByEmail(ctx context.Context, email string) (*User, error) {
var user User
filter := bson.M{"email": email}
err := r.collection.FindOne(ctx, filter).Decode(&user)
user, err := r.ormRepo.FindOne(ctx, filter)
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
return nil, errors.New("user not found")
}
r.logger.Error("Failed to get user by email", map[string]interface{}{
@@ -177,18 +121,15 @@ func (r *userRepository) GetByEmail(ctx context.Context, email string) (*User, e
return nil, err
}
return &user, nil
return user, nil
}
// GetByUsername retrieves a user by username
func (r *userRepository) GetByUsername(ctx context.Context, username string) (*User, error) {
var user User
filter := bson.M{"username": username}
err := r.collection.FindOne(ctx, filter).Decode(&user)
user, err := r.ormRepo.FindOne(ctx, filter)
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
return nil, errors.New("user not found")
}
r.logger.Error("Failed to get user by username", map[string]interface{}{
@@ -198,32 +139,26 @@ func (r *userRepository) GetByUsername(ctx context.Context, username string) (*U
return nil, err
}
return &user, nil
return user, nil
}
// Update updates a user
func (r *userRepository) Update(ctx context.Context, user *User) error {
// Set updated timestamp using Unix timestamp
user.UpdatedAt = time.Now().Unix()
user.SetUpdatedAt(time.Now().Unix())
filter := bson.M{"_id": user.ID}
update := bson.M{"$set": user}
result, err := r.collection.UpdateOne(ctx, filter, update)
// Use ORM to update user
err := r.ormRepo.Update(ctx, user)
if err != nil {
r.logger.Error("Failed to update user", map[string]interface{}{
"error": err.Error(),
"user_id": user.ID.String(),
"user_id": user.ID,
})
return err
}
if result.MatchedCount == 0 {
return errors.New("user not found")
}
r.logger.Info("User updated successfully", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
})
@@ -231,30 +166,29 @@ func (r *userRepository) Update(ctx context.Context, user *User) error {
}
// Delete deletes a user (soft delete by setting status to inactive)
func (r *userRepository) Delete(ctx context.Context, id uuid.UUID) error {
filter := bson.M{"_id": id}
update := bson.M{
"$set": bson.M{
"status": UserStatusInactive,
"updated_at": time.Now().Unix(),
},
func (r *userRepository) Delete(ctx context.Context, id string) error {
// Get user first
user, err := r.GetByID(ctx, id)
if err != nil {
return err
}
result, err := r.collection.UpdateOne(ctx, filter, update)
// Update status to inactive
user.Status = UserStatusInactive
user.SetUpdatedAt(time.Now().Unix())
// Update in database
err = r.ormRepo.Update(ctx, user)
if err != nil {
r.logger.Error("Failed to delete user", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
})
return err
}
if result.MatchedCount == 0 {
return errors.New("user not found")
}
r.logger.Info("User deleted successfully", map[string]interface{}{
"user_id": id.String(),
"user_id": id,
})
return nil
@@ -262,18 +196,18 @@ func (r *userRepository) Delete(ctx context.Context, id uuid.UUID) error {
// List retrieves users with pagination
func (r *userRepository) List(ctx context.Context, limit, offset int) ([]*User, error) {
var users []*User
// Build options
opts := options.Find()
opts.SetLimit(int64(limit))
opts.SetSkip(int64(offset))
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
// Build pagination
pagination := mongopkg.NewPaginationBuilder().
Limit(limit).
Skip(offset).
SortDesc("created_at").
Build()
// Only active users by default
filter := bson.M{"status": bson.M{"$ne": UserStatusInactive}}
cursor, err := r.collection.Find(ctx, filter, opts)
// Use ORM to find users
result, err := r.ormRepo.FindAll(ctx, filter, pagination)
if err != nil {
r.logger.Error("Failed to list users", map[string]interface{}{
"error": err.Error(),
@@ -282,22 +216,18 @@ func (r *userRepository) List(ctx context.Context, limit, offset int) ([]*User,
})
return nil, err
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &users); err != nil {
r.logger.Error("Failed to decode users", map[string]interface{}{
"error": err.Error(),
})
return nil, err
// Convert []User to []*User
users := make([]*User, len(result.Items))
for i := range result.Items {
users[i] = &result.Items[i]
}
return users, nil
}
// Search retrieves users with search and filters
func (r *userRepository) Search(ctx context.Context, search string, status *string, role *string, companyID *uuid.UUID, limit, offset int, sortBy, sortOrder string) ([]*User, error) {
var users []*User
func (r *userRepository) Search(ctx context.Context, search string, status *string, role *string, companyID *string, limit, offset int, sortBy, sortOrder string) ([]*User, error) {
// Build filter
filter := bson.M{}
@@ -317,23 +247,24 @@ func (r *userRepository) Search(ctx context.Context, search string, status *stri
filter["company_id"] = *companyID
}
// Build options
opts := options.Find()
opts.SetLimit(int64(limit))
opts.SetSkip(int64(offset))
// Build pagination
pagination := mongopkg.NewPaginationBuilder().
Limit(limit).
Skip(offset)
// Set sort
if sortBy != "" {
sortValue := 1
if sortOrder == "desc" {
sortValue = -1
pagination.SortDesc(sortBy)
} else {
pagination.SortAsc(sortBy)
}
opts.SetSort(bson.D{{Key: sortBy, Value: sortValue}})
} else {
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Default sort
pagination.SortDesc("created_at") // Default sort
}
cursor, err := r.collection.Find(ctx, filter, opts)
// Use ORM to find users
result, err := r.ormRepo.FindAll(ctx, filter, pagination.Build())
if err != nil {
r.logger.Error("Failed to search users", map[string]interface{}{
"error": err.Error(),
@@ -341,27 +272,24 @@ func (r *userRepository) Search(ctx context.Context, search string, status *stri
})
return nil, err
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &users); err != nil {
r.logger.Error("Failed to decode users from search", map[string]interface{}{
"error": err.Error(),
})
return nil, err
// Convert []User to []*User
users := make([]*User, len(result.Items))
for i := range result.Items {
users[i] = &result.Items[i]
}
return users, nil
}
// GetByCompanyID retrieves users by company ID with pagination
func (r *userRepository) GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, error) {
var users []*User
// Build options
opts := options.Find()
opts.SetLimit(int64(limit))
opts.SetSkip(int64(offset))
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
func (r *userRepository) GetByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*User, error) {
// Build pagination
pagination := mongopkg.NewPaginationBuilder().
Limit(limit).
Skip(offset).
SortDesc("created_at").
Build()
// Filter by company ID and active status
filter := bson.M{
@@ -369,24 +297,22 @@ func (r *userRepository) GetByCompanyID(ctx context.Context, companyID uuid.UUID
"status": bson.M{"$ne": UserStatusInactive},
}
cursor, err := r.collection.Find(ctx, filter, opts)
// Use ORM to find users
result, err := r.ormRepo.FindAll(ctx, filter, pagination)
if err != nil {
r.logger.Error("Failed to get users by company ID", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
"company_id": companyID,
"limit": limit,
"offset": offset,
})
return nil, err
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &users); err != nil {
r.logger.Error("Failed to decode users by company", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
})
return nil, err
// Convert []User to []*User
users := make([]*User, len(result.Items))
for i := range result.Items {
users[i] = &result.Items[i]
}
return users, nil
@@ -394,13 +320,12 @@ func (r *userRepository) GetByCompanyID(ctx context.Context, companyID uuid.UUID
// GetByRole retrieves users by role with pagination
func (r *userRepository) GetByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error) {
var users []*User
// Build options
opts := options.Find()
opts.SetLimit(int64(limit))
opts.SetSkip(int64(offset))
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
// Build pagination
pagination := mongopkg.NewPaginationBuilder().
Limit(limit).
Skip(offset).
SortDesc("created_at").
Build()
// Filter by role and active status
filter := bson.M{
@@ -408,7 +333,8 @@ func (r *userRepository) GetByRole(ctx context.Context, role UserRole, limit, of
"status": bson.M{"$ne": UserStatusInactive},
}
cursor, err := r.collection.Find(ctx, filter, opts)
// Use ORM to find users
result, err := r.ormRepo.FindAll(ctx, filter, pagination)
if err != nil {
r.logger.Error("Failed to get users by role", map[string]interface{}{
"error": err.Error(),
@@ -418,61 +344,57 @@ func (r *userRepository) GetByRole(ctx context.Context, role UserRole, limit, of
})
return nil, err
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &users); err != nil {
r.logger.Error("Failed to decode users by role", map[string]interface{}{
"error": err.Error(),
"role": role,
})
return nil, err
// Convert []User to []*User
users := make([]*User, len(result.Items))
for i := range result.Items {
users[i] = &result.Items[i]
}
return users, nil
}
// UpdateLastLogin updates the last login timestamp
func (r *userRepository) UpdateLastLogin(ctx context.Context, id uuid.UUID) error {
filter := bson.M{"_id": id}
update := bson.M{
"$set": bson.M{
"last_login_at": time.Now().Unix(),
"updated_at": time.Now().Unix(),
},
func (r *userRepository) UpdateLastLogin(ctx context.Context, id string) error {
// Get user first
user, err := r.GetByID(ctx, id)
if err != nil {
return err
}
result, err := r.collection.UpdateOne(ctx, filter, update)
// Update last login timestamp
user.LastLoginAt = &[]int64{time.Now().Unix()}[0]
user.SetUpdatedAt(time.Now().Unix())
// Update in database
err = r.ormRepo.Update(ctx, user)
if err != nil {
r.logger.Error("Failed to update last login", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
})
return err
}
if result.MatchedCount == 0 {
return errors.New("user not found")
}
r.logger.Info("Last login updated successfully", map[string]interface{}{
"user_id": id.String(),
"user_id": id,
})
return nil
}
// CountByCompanyID counts users by company ID
func (r *userRepository) CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error) {
func (r *userRepository) CountByCompanyID(ctx context.Context, companyID string) (int64, error) {
filter := bson.M{
"company_id": companyID,
"status": bson.M{"$ne": UserStatusInactive},
}
count, err := r.collection.CountDocuments(ctx, filter)
count, err := r.ormRepo.Count(ctx, filter)
if err != nil {
r.logger.Error("Failed to count users by company ID", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
"company_id": companyID,
})
return 0, err
}