89 lines
2.1 KiB
Go
89 lines
2.1 KiB
Go
package repository
|
|
|
|
import (
|
|
"apskel-pos-be/internal/entities"
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type GameRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewGameRepository(db *gorm.DB) *GameRepository {
|
|
return &GameRepository{db: db}
|
|
}
|
|
|
|
func (r *GameRepository) Create(ctx context.Context, game *entities.Game) error {
|
|
return r.db.WithContext(ctx).Create(game).Error
|
|
}
|
|
|
|
func (r *GameRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.Game, error) {
|
|
var game entities.Game
|
|
err := r.db.WithContext(ctx).Preload("Prizes").Where("id = ?", id).First(&game).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &game, nil
|
|
}
|
|
|
|
func (r *GameRepository) List(ctx context.Context, offset, limit int, search, gameType string, isActive *bool, sortBy, sortOrder string) ([]entities.Game, int64, error) {
|
|
var games []entities.Game
|
|
var total int64
|
|
|
|
query := r.db.WithContext(ctx).Preload("Prizes")
|
|
|
|
if search != "" {
|
|
searchTerm := "%" + search + "%"
|
|
query = query.Where("name ILIKE ?", searchTerm)
|
|
}
|
|
|
|
if gameType != "" {
|
|
query = query.Where("type = ?", gameType)
|
|
}
|
|
|
|
if isActive != nil {
|
|
query = query.Where("is_active = ?", *isActive)
|
|
}
|
|
|
|
if err := query.Model(&entities.Game{}).Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
if sortBy != "" {
|
|
if sortOrder == "" {
|
|
sortOrder = "asc"
|
|
}
|
|
query = query.Order(fmt.Sprintf("%s %s", sortBy, sortOrder))
|
|
} else {
|
|
query = query.Order("created_at DESC")
|
|
}
|
|
|
|
err := query.Offset(offset).Limit(limit).Find(&games).Error
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return games, total, nil
|
|
}
|
|
|
|
func (r *GameRepository) Update(ctx context.Context, game *entities.Game) error {
|
|
return r.db.WithContext(ctx).Save(game).Error
|
|
}
|
|
|
|
func (r *GameRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
|
return r.db.WithContext(ctx).Delete(&entities.Game{}, id).Error
|
|
}
|
|
|
|
func (r *GameRepository) GetActiveGames(ctx context.Context) ([]entities.Game, error) {
|
|
var games []entities.Game
|
|
err := r.db.WithContext(ctx).Preload("Prizes").Where("is_active = ?", true).Find(&games).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return games, nil
|
|
}
|