Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
// Package chat is the chats module. Entities mirror future table rows and
|
||||
// carry no behaviour; membership is a query rather than a field, and
|
||||
// ChatWithMembers is the projection the API renders. Both entities derive
|
||||
// CreatedAt from their UUIDv7 id, so the history order (created_at, id) is
|
||||
// plain id order.
|
||||
package chat
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxTitleCodePoints = 100
|
||||
MaxMembers = 100
|
||||
)
|
||||
|
||||
// ErrNotFound covers both a missing chat and a chat the caller is not a
|
||||
// member of, so outsiders cannot probe for existence.
|
||||
var ErrNotFound = apperr.NotFound("chat not found")
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatWithMembers struct {
|
||||
Chat
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
func NewChat(id uuid.UUID, title string) (Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return Chat{}, apperr.Invalid("title must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(title) > MaxTitleCodePoints {
|
||||
return Chat{}, apperr.Invalid(fmt.Sprintf("title must be at most %d characters", MaxTitleCodePoints))
|
||||
}
|
||||
return Chat{ID: id, Title: title, CreatedAt: ident.TimeOf(id)}, nil
|
||||
}
|
||||
|
||||
// ValidateMembers checks the member list of a new chat and returns its own
|
||||
// copy in the original order.
|
||||
func ValidateMembers(memberIDs []uuid.UUID, creator uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(memberIDs) == 0 {
|
||||
return nil, apperr.Invalid("member_ids must not be empty")
|
||||
}
|
||||
if len(memberIDs) > MaxMembers {
|
||||
return nil, apperr.Invalid(fmt.Sprintf("member_ids must have at most %d entries", MaxMembers))
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, m := range memberIDs {
|
||||
if m == uuid.Nil {
|
||||
return nil, apperr.Invalid("member_ids must not contain the nil uuid")
|
||||
}
|
||||
if _, dup := seen[m]; dup {
|
||||
return nil, apperr.Invalid("member_ids must be unique")
|
||||
}
|
||||
seen[m] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[creator]; !ok {
|
||||
return nil, apperr.Invalid("member_ids must include the creator")
|
||||
}
|
||||
return append([]uuid.UUID(nil), memberIDs...), nil
|
||||
}
|
||||
Reference in New Issue
Block a user