nquest/pkg/service/game.go

78 lines
1.5 KiB
Go
Raw Normal View History

2023-11-01 23:21:12 +03:00
package service
import (
"context"
"gitrepo.ru/neonxp/nquest/pkg/models"
"gorm.io/gorm"
)
type Game struct {
DB *gorm.DB
}
// NewGame returns new Game.
func NewGame(db *gorm.DB) *Game {
return &Game{
DB: db,
}
}
func (gs *Game) GetByID(ctx context.Context, id uint) (*models.Game, error) {
g := &models.Game{}
return g, gs.DB.
WithContext(ctx).
2024-01-05 03:50:33 +03:00
Preload("Tasks").
2023-11-01 23:21:12 +03:00
First(g, id).
Error
}
func (gs *Game) List(ctx context.Context) ([]*models.Game, error) {
games := make([]*models.Game, 0)
return games, gs.DB.
WithContext(ctx).
2024-01-05 03:50:33 +03:00
Order("created_at DESC").
2023-11-01 23:21:12 +03:00
Find(&games, "visible = true").
Limit(20).
Error
}
func (gs *Game) GetTaskID(ctx context.Context, id uint) (*models.Task, error) {
t := &models.Task{}
return t, gs.DB.WithContext(ctx).Preload("Next").First(t, id).Error
}
2023-11-19 22:54:54 +03:00
func (gs *Game) ListByAuthor(ctx context.Context, author *models.User) ([]*models.Game, error) {
games := make([]*models.Game, 0)
return games, gs.DB.
WithContext(ctx).
Model(&models.Game{}).
Preload("Authors", gs.DB.Where("id = ?", author.ID)).
Order("created_at DESC").
Find(&games).
Limit(20).
Error
}
2024-01-05 03:50:33 +03:00
func (gs *Game) CreateGame(ctx context.Context, game *models.Game) (*models.Game, error) {
return game, gs.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(game).Error; err != nil {
return err
}
for i, t := range game.Tasks {
if i < len(game.Tasks)-1 {
t.Next = game.Tasks[i+1]
if err := tx.Save(t).Error; err != nil {
return err
}
}
}
return nil
})
}