Files
mtusi2026lab2/internal/user/user.go
T

52 lines
1.3 KiB
Go

// Package user is the users module. The entity mirrors the future table row
// and carries no behaviour; New only enforces input invariants and CreatedAt
// derives from the UUIDv7 id.
package user
import (
"fmt"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const MaxDisplayNameCodePoints = 100
var (
ErrNotFound = apperr.NotFound("user not found")
ErrUsernameTaken = apperr.Conflict("username already taken")
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type User struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func New(id uuid.UUID, username, displayName string) (User, error) {
if !usernamePattern.MatchString(username) {
return User{}, apperr.Invalid("username must match [a-z0-9_]{3,32}")
}
if strings.TrimSpace(displayName) == "" {
return User{}, apperr.Invalid("display_name must not be blank")
}
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
}
return User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: ident.TimeOf(id),
}, nil
}