forked from mtusi2026/mtusi2026lab3
70 lines
1.9 KiB
Go
70 lines
1.9 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) 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 {
|
|
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
|
|
}
|