Files
mtusi2026lab2_fork/backend/internal/service/user.go
T

77 lines
1.8 KiB
Go

package service
import (
"context"
"errors"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type UserService struct {
users domain.UserRepository
}
func NewUserService(users domain.UserRepository) *UserService {
return &UserService{users: users}
}
func (s *UserService) Create(ctx context.Context, username, displayName string) (*domain.User, error) {
if !usernamePattern.MatchString(username) {
return nil, &domain.ValidationError{
Field: "username",
Message: "должен соответствовать ^[a-z0-9_]{3,32}$",
}
}
if strings.TrimSpace(displayName) == "" {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(displayName) > 100 {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не более 100 символов",
}
}
_, err := s.users.GetByUsername(ctx, username)
if err == nil {
return nil, &domain.AlreadyExistsError{
Entity: "user",
Field: "username",
Value: username,
}
}
if !errors.Is(err, domain.ErrNotFound) {
return nil, err
}
u := &domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC(),
}
if err := s.users.Create(ctx, u); err != nil {
return nil, err
}
return u, nil
}
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
return s.users.GetByID(ctx, id)
}
func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
return s.users.GetByUsername(ctx, username)
}