This commit is contained in:
2026-09-10 02:39:55 +07:00
parent 79bd3e2cf8
commit 9986d593d3
5 changed files with 196 additions and 8 deletions
@@ -0,0 +1,77 @@
package screen_sessions_repo
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrScreenNotFound = errors.New("Экран не найден")
type ScreenSession struct {
ID int
GameID *int
}
type ScreenSessionsRepo struct {
pool *pgxpool.Pool
}
func NewScreenSessionsRepo(pool *pgxpool.Pool) *ScreenSessionsRepo {
return &ScreenSessionsRepo{pool: pool}
}
func (r *ScreenSessionsRepo) Create(ctx context.Context, tokenHash string) (int, error) {
var id int
err := r.pool.QueryRow(ctx, `
INSERT INTO screen_sessions (access_token_hash)
VALUES ($1)
RETURNING id`, tokenHash).Scan(&id)
return id, err
}
func (r *ScreenSessionsRepo) Get(ctx context.Context, id int, tokenHash string) (*ScreenSession, error) {
session := &ScreenSession{ID: id}
err := r.pool.QueryRow(ctx, `
SELECT game_id
FROM screen_sessions
WHERE id = $1 AND access_token_hash = $2`, id, tokenHash).
Scan(&session.GameID)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrScreenNotFound
}
if err != nil {
return nil, err
}
return session, nil
}
func (r *ScreenSessionsRepo) Bind(ctx context.Context, id, gameID int, tokenHash string) error {
result, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
SET game_id = $1, updated_at = NOW()
WHERE id = $2 AND access_token_hash = $3`, gameID, id, tokenHash)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return ErrScreenNotFound
}
return nil
}
func (r *ScreenSessionsRepo) Unbind(ctx context.Context, id int) error {
result, err := r.pool.Exec(ctx, `
UPDATE screen_sessions
SET game_id = NULL, updated_at = NOW()
WHERE id = $1`, id)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return ErrScreenNotFound
}
return nil
}