Files
mtusi2026lab3/internal/chat/message.go
T

51 lines
1.2 KiB
Go

package chat
import (
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const MaxTextCodePoints = 4000
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
// NewMessage keeps the text verbatim; only blank or oversized text is rejected.
func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
if strings.TrimSpace(text) == "" {
return Message{}, apperr.Invalid("text must not be blank")
}
if utf8.RuneCountInString(text) > MaxTextCodePoints {
return Message{}, apperr.Invalid(fmt.Sprintf("text must be at most %d characters", MaxTextCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(text, 0) {
return Message{}, apperr.Invalid("text must not contain the NUL character")
}
return Message{
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: ident.TimeOf(id),
}, nil
}
// SameContent reports whether two messages say the same thing, whatever their
// ids and times.
func (m Message) SameContent(other Message) bool {
return m.Text == other.Text
}