refactor(app) agent refactoring + a little review

This commit is contained in:
imadev
2026-10-31 20:22:16 +03:00
parent 2ef20e7040
commit 362ba16cc4
25 changed files with 240 additions and 375 deletions
+16 -19
View File
@@ -21,15 +21,14 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.U
}
defer rollback(tx)
for _, memberID := range memberIDs {
var exists int
err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
}
if err != nil {
return model.Chat{}, dbError(err)
}
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{
@@ -64,19 +63,12 @@ func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (m
ctx, cancel := s.withTimeout(ctx)
defer cancel()
chat, err := scanChat(s.pool.QueryRow(ctx, `
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))
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.NotFound("chat not found")
}
if err != nil {
return model.Chat{}, dbError(err)
}
return chat, nil
}
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
@@ -101,7 +93,7 @@ func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, curs
for rows.Next() {
chat, scanErr := scanChat(rows)
if scanErr != nil {
return nil, dbError(scanErr)
return nil, scanErr
}
chats = append(chats, chat)
}
@@ -134,11 +126,16 @@ func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, e
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 {
return model.Chat{}, err
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