57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package storage
|
|
|
|
import (
|
|
"backend/internal/domain"
|
|
"backend/internal/repository/storage/types"
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type SessionRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewSessionRepository(db *gorm.DB) domain.SessionRepo {
|
|
return &SessionRepository{
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (r *SessionRepository) Create(ctx context.Context, session *domain.UserSession) error {
|
|
model := types.CastSessionToStorage(*session)
|
|
return r.db.WithContext(ctx).Create(&model).Error
|
|
}
|
|
|
|
func (r *SessionRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.UserSession, error) {
|
|
var session types.UserSession
|
|
if err := r.db.WithContext(ctx).Preload("User").First(&session, "id = ?", id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return types.CastSessionToDomain(session), nil
|
|
}
|
|
|
|
func (r *SessionRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
|
var session types.UserSession
|
|
if err := r.db.WithContext(ctx).First(&session, "id = ?", id).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
return r.db.WithContext(ctx).Delete(&session).Error
|
|
}
|
|
|
|
func (r *SessionRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]domain.UserSession, error) {
|
|
var sessions []types.UserSession
|
|
if err := r.db.WithContext(ctx).Preload("User").Find(&sessions, "user_id = ?", userID).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
result := make([]domain.UserSession, len(sessions))
|
|
for i, session := range sessions {
|
|
result[i] = *types.CastSessionToDomain(session)
|
|
}
|
|
return result, nil
|
|
}
|