add bulk users

This commit is contained in:
Aditya Siregar
2025-08-15 22:42:58 +07:00
parent e1a5e9efd3
commit 5966301165
8 changed files with 313 additions and 25 deletions
+10 -16
View File
@@ -317,13 +317,11 @@ func (p *UserProcessorImpl) GetActiveUsersForMention(ctx context.Context, search
func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context, userRequests []contract.BulkUserRequest) ([]contract.UserResponse, []contract.BulkUserErrorResult, error) {
created := []contract.UserResponse{}
failed := []contract.BulkUserErrorResult{}
// Pre-validate all users
usersToCreate := []*entities.User{}
emailMap := make(map[string]bool)
for _, req := range userRequests {
// Check for duplicate emails in the batch
if emailMap[req.Email] {
failed = append(failed, contract.BulkUserErrorResult{
User: req,
@@ -332,8 +330,7 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
continue
}
emailMap[req.Email] = true
// Check if email already exists in database
existing, _ := p.userRepo.GetByEmail(ctx, req.Email)
if existing != nil {
failed = append(failed, contract.BulkUserErrorResult{
@@ -342,8 +339,7 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
})
continue
}
// Hash password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
failed = append(failed, contract.BulkUserErrorResult{
@@ -352,8 +348,7 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
})
continue
}
// Create user entity
user := &entities.User{
ID: uuid.New(),
Name: req.Name,
@@ -361,11 +356,10 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
PasswordHash: string(hashedPassword),
IsActive: true,
}
usersToCreate = append(usersToCreate, user)
}
// Bulk create valid users
if len(usersToCreate) > 0 {
// Use CreateInBatches for large datasets
err := p.userRepo.CreateInBatches(ctx, usersToCreate, 50)
@@ -385,7 +379,7 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
FullName: user.Name,
}
_ = p.profileRepo.Create(ctx, profile)
created = append(created, *transformer.EntityToContract(user))
}
}
@@ -397,11 +391,11 @@ func (p *UserProcessorImpl) BulkCreateUsersWithTransaction(ctx context.Context,
FullName: user.Name,
}
_ = p.profileRepo.Create(ctx, profile)
created = append(created, *transformer.EntityToContract(user))
}
}
}
return created, failed, nil
}