Create chat/ package with Message type, Room (NATS pub/sub + buffer), DB persistence helpers, and a unified templ component parameterized by Config (CSS prefix, post URL, color function, key propagation). Both c4game and snakegame now use chat.Room for message management and chatcomponents.Chat for rendering, eliminating the duplicated ChatMessage types, chat templ components, chatAutoScroll scripts, color functions, and inline buffer management.
46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package chat
|
|
|
|
import (
|
|
"context"
|
|
"slices"
|
|
|
|
"github.com/ryanhamamura/c4/db/repository"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// SaveMessage persists a chat message to the database.
|
|
func SaveMessage(queries *repository.Queries, roomID string, msg Message) {
|
|
err := queries.CreateChatMessage(context.Background(), repository.CreateChatMessageParams{
|
|
GameID: roomID,
|
|
Nickname: msg.Nickname,
|
|
Color: int64(msg.Slot),
|
|
Message: msg.Message,
|
|
CreatedAt: msg.Time,
|
|
})
|
|
if err != nil {
|
|
log.Error().Err(err).Str("room_id", roomID).Msg("failed to save chat message")
|
|
}
|
|
}
|
|
|
|
// LoadMessages loads persisted chat messages for a room, returning them
|
|
// in chronological order (oldest first).
|
|
func LoadMessages(queries *repository.Queries, roomID string) []Message {
|
|
rows, err := queries.GetChatMessages(context.Background(), roomID)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
msgs := make([]Message, len(rows))
|
|
for i, r := range rows {
|
|
msgs[i] = Message{
|
|
Nickname: r.Nickname,
|
|
Slot: int(r.Color),
|
|
Message: r.Message,
|
|
Time: r.CreatedAt,
|
|
}
|
|
}
|
|
// DB returns newest-first; reverse for chronological display
|
|
slices.Reverse(msgs)
|
|
return msgs
|
|
}
|