forked from mtusi2026/mtusi2026lab2
refactor(app) AI refactoring before moving to Lab3 done
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: passwordHash,
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
|
||||
if err != nil {
|
||||
// AGENT: The unique index is the real guard. Two concurrent registrations
|
||||
// with the same username both reach INSERT; exactly one commits, the other
|
||||
// gets SQLSTATE 23505 and is mapped to 409 instead of a 500.
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, common.Conflict("username already taken")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username))
|
||||
}
|
||||
|
||||
func (s *Store) scanUser(row rowScanner) (model.User, error) {
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, common.NotFound("user not found")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
user.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return user, nil
|
||||
}
|
||||
Reference in New Issue
Block a user