feat: перенос 5 лабы логики
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import asyncpg
|
||||
|
||||
from domain import UserCredentialsSchema, UserSchema
|
||||
from domain.errors import ConflictError
|
||||
from infrastructure.utils import Pool, repository_logs
|
||||
from interfaces import UserRepository
|
||||
|
||||
|
||||
class PostgresUserRepository(UserRepository):
|
||||
def __init__(self, pool: Pool) -> None:
|
||||
self._pool = pool
|
||||
|
||||
@repository_logs
|
||||
async def create(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> UserSchema:
|
||||
query = """
|
||||
INSERT INTO users
|
||||
(
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
$1,
|
||||
$2,
|
||||
$3
|
||||
)
|
||||
RETURNING id, username, display_name, created_at;
|
||||
"""
|
||||
async with self._pool.acquire() as conn:
|
||||
try:
|
||||
row = await conn.fetchrow(query, username, display_name, password_hash)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ConflictError("Имя пользователя уже занято") from None
|
||||
assert row is not None
|
||||
return self._row_to_user(row)
|
||||
|
||||
@repository_logs
|
||||
async def get_credentials(self, username: str) -> UserCredentialsSchema | None:
|
||||
query = """
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
created_at,
|
||||
password_hash
|
||||
FROM users
|
||||
WHERE username = $1;
|
||||
"""
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(query, username)
|
||||
if row is None:
|
||||
return None
|
||||
return UserCredentialsSchema(
|
||||
user=self._row_to_user(row), password_hash=row["password_hash"]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _row_to_user(row: asyncpg.Record) -> UserSchema:
|
||||
return UserSchema(
|
||||
id=row["id"],
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
Reference in New Issue
Block a user