Files
mtusi2026lab4/internal/storage/postgres/user_repository.go
T
2026-10-15 20:45:29 +03:00

64 lines
1.5 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type UserRepository struct {
store *Store
}
func (r *UserRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateUser(ctx, sqlcgen.CreateUserParams{
Username: draft.Username,
DisplayName: draft.DisplayName,
PasswordHash: draft.PasswordHash,
})
if err != nil {
if isUniqueViolation(err) {
return domain.User{}, fmt.Errorf("%w: username %q", domain.ErrUsernameTaken, draft.Username)
}
return domain.User{}, fmt.Errorf("create user: %w", mapError(err))
}
return domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
}, nil
}
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetUserByID(ctx, id)
if err != nil {
mapped := mapError(err)
if errors.Is(mapped, domain.ErrNotFound) {
return domain.User{}, fmt.Errorf("%w: user %s", domain.ErrNotFound, id)
}
return domain.User{}, fmt.Errorf("get user: %w", mapped)
}
return domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
}, nil
}