forked from mtusi2026/mtusi2026lab2
59 lines
1.7 KiB
Go
59 lines
1.7 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/charawein/mtusi2026lab2/internal/domain"
|
|
"github.com/charawein/mtusi2026lab2/internal/repository"
|
|
)
|
|
|
|
type SessionRepository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
|
|
return &SessionRepository{pool: pool}
|
|
}
|
|
|
|
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
|
const q = `INSERT INTO sessions (token, user_id, expires_at, created_at) VALUES ($1, $2, $3, $4)`
|
|
if _, err := r.pool.Exec(ctx, q, s.Token, s.UserID, s.ExpiresAt, s.CreatedAt); err != nil {
|
|
return fmt.Errorf("insert session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
|
const q = `SELECT token, user_id, expires_at, created_at FROM sessions WHERE token = $1`
|
|
var s domain.Session
|
|
err := r.pool.QueryRow(ctx, q, token).Scan(&s.Token, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, repository.ErrNotFound
|
|
}
|
|
return nil, fmt.Errorf("select session: %w", err)
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
|
const q = `DELETE FROM sessions WHERE token = $1`
|
|
if _, err := r.pool.Exec(ctx, q, token); err != nil {
|
|
return fmt.Errorf("delete session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
|
const q = `DELETE FROM sessions WHERE expires_at < now()`
|
|
if _, err := r.pool.Exec(ctx, q); err != nil {
|
|
return fmt.Errorf("delete expired: %w", err)
|
|
}
|
|
return nil
|
|
}
|