2024-10-13 13:31:58 +04:00

50 lines
1.1 KiB
Go

package service
import (
"context"
"github.com/aykhans/oh-my-chat/internal/core/domain"
"github.com/aykhans/oh-my-chat/internal/core/port"
"github.com/aykhans/oh-my-chat/internal/core/utils"
)
type UserService struct {
repo port.UserRepository
}
func NewUserService(repo port.UserRepository) *UserService {
return &UserService{repo: repo}
}
func (userService *UserService) Register(
ctx context.Context,
user *domain.User,
) (*domain.User, error) {
if exists, err := userService.repo.IsUsernameExists(ctx, user.Username); err != nil {
return nil, domain.ErrInternal
} else if exists {
return nil, domain.ErrUsernameExists
}
if exists, err := userService.repo.IsEmailExists(ctx, user.Email); err != nil {
return nil, domain.ErrInternal
} else if exists {
return nil, domain.ErrEmailExists
}
hashedPassword, err := utils.HashPassword(user.Password)
if err != nil {
return nil, domain.ErrInternal
}
user.Password = hashedPassword
user, err = userService.repo.CreateUser(ctx, user)
if err != nil {
if err == domain.ErrConflictingData {
return nil, err
}
return nil, domain.ErrInternal
}
return user, nil
}