Files

143 lines
3.8 KiB
Go

package store
import (
"context"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, dbError(err)
}
defer rollback(tx)
var existing int
if err = tx.QueryRow(ctx,
`SELECT count(*) FROM users WHERE id = ANY($1::uuid[])`,
memberIDs).Scan(&existing); err != nil {
return model.Chat{}, dbError(err)
}
if existing != len(memberIDs) {
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
}
chat := model.Chat{
ID: uuid.New(),
Title: title,
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
CreatedAt: common.NowUTC(),
}
if _, err = tx.Exec(ctx,
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil {
return model.Chat{}, dbError(err)
}
for _, memberID := range memberIDs {
if _, err = tx.Exec(ctx,
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
chat.ID, memberID); err != nil {
return model.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return model.Chat{}, dbError(err)
}
return chat, nil
}
func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return scanChat(s.pool.QueryRow(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
WHERE c.id = $1`, chatID, userID))
}
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
cursorTime, cursorID := cursorValues(cursor)
rows, err := s.pool.Query(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
WHERE (c.created_at, c.id) > ($2, $3)
ORDER BY c.created_at, c.id
LIMIT $4`, userID, cursorTime, cursorID, limit+1)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]model.Chat, 0, limit)
for rows.Next() {
chat, scanErr := scanChat(rows)
if scanErr != nil {
return nil, scanErr
}
chats = append(chats, chat)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
hasMore := len(chats) > limit
if hasMore {
chats = chats[:limit]
}
return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil
}
func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
var exists int
err := s.pool.QueryRow(ctx,
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
chatID, userID).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, dbError(err)
}
return true, nil
}
// scanChat owns the "row is missing" meaning for single-row lookups; list
// queries never see ErrNoRows.
func scanChat(row rowScanner) (model.Chat, error) {
var chat model.Chat
var createdAt time.Time
if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.NotFound("chat not found")
}
return model.Chat{}, dbError(err)
}
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
return chat, nil
}